2011-04-12 93 views
0

鑑於以下模型,我的目標是創建一個QuerySet,以便爲給定的PostCategory ID提取所有可用的Tag對象。我知道如何在SQL中編寫它,但不知道如何使用Django ORM來完成。我相信我通過定義Post對象上的關係來遵循最佳實踐,而不是標記,但是QuerySet語法模式看起來像期望我以Tag.objects.filter()開始,但我不知道如何。Django QuerySet連接四個表,包括ManyToMany?

class Tag(models.Model): 
    name = models.CharField(max_length=255) 

class PostCategory(models.Model): 
    name = models.CharField(max_length=100)  

class Post(models.Model): 
    body_text = models.TextField() 
    pub_date = models.DateTimeField() 
    mod_date = models.DateTimeField(auto_now=True) 
    title = models.CharField(max_length=255) 
    subtitle = models.CharField(max_length=255) 
    is_featured = models.BooleanField() 
    image = models.ImageField(upload_to='post_images') 
    tags = models.ManyToManyField(Tag, null=True, blank=True) 
    user = models.ForeignKey(User) 
    category = models.ForeignKey(PostCategory) 

回答

1
tags = Tag.objects.filter(post__category_id=postcategory_id).distinct() 
+0

你打我吧,我理解了它我得到通知的答案:)感謝之前! – shawnwall 2011-04-12 02:42:21