Django QuerySet连接四个表,包括ManyToMany?

时间:2011-04-12 02:22:48

标签: django many-to-many django-queryset

鉴于以下模型,我的目标是创建一个QuerySet,为给定的PostCategory id提取所有可用的Tag对象。我知道如何在SQL中编写它,但无法弄清楚如何使用Django ORM。我相信我通过在Post对象上定义关系来遵循最佳实践,而不是Tag,但是QuerySet语法模式似乎希望我从Tag.objects.filter()开始,但我不知道如何。

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 个答案:

答案 0 :(得分:1)

tags = Tag.objects.filter(post__category_id=postcategory_id).distinct()