如何根据引用对象的数量来过滤对象?

时间:2012-03-01 20:45:04

标签: python django

假设我正在构建这样的文章/评论系统:

class Article(models.Model):
    title = models.TextField()
    content = models.TextField()

class Comment(models.Model):
    article = ForeignKey(Article)
    content = models.TextField()

如何过滤Article.objects以查找评论超过十条的文章?

3 个答案:

答案 0 :(得分:2)

您需要annotate您的查询集,其中包含每篇文章的评论数量,然后在带注释的字段上进行过滤。

from django.db.models import Count
Article.objects.annotate(num_comments=Count('comment')).filter(num_comments__gt=10)

答案 1 :(得分:1)

from django.db.models import Count

Article.objects.annotate(comment_count=Count('comment')).filter(comment_count__gte=10)

答案 2 :(得分:1)

请参阅https://docs.djangoproject.com/en/dev/topics/db/aggregation/#aggregating-annotations中的此示例:

 Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)
相关问题