假设我正在构建这样的文章/评论系统:
class Article(models.Model):
title = models.TextField()
content = models.TextField()
class Comment(models.Model):
article = ForeignKey(Article)
content = models.TextField()
如何过滤Article.objects
以查找评论超过十条的文章?
答案 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)