如何通过有多少个对象引用它们来筛选对象?

2024-04-23 10:12:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我如何筛选Article.objects以查找评论超过10条的文章?你知道吗


Tags: modelobjectstitlemodels系统article文章comment
3条回答

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

 Book.objects.annotate(num_authors=Count('authors')).filter(num_authors__gt=1)

您需要annotate您的queryset为每篇文章设置注释的数量,然后在注释字段上进行筛选。你知道吗

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

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

相关问题 更多 >