2024-04-23 10:12:46 发布
网友
假设我正在构建一个这样的文章/评论系统:
class Article(models.Model): title = models.TextField() content = models.TextField() class Comment(models.Model): article = ForeignKey(Article) content = models.TextField()
我如何筛选Article.objects以查找评论超过10条的文章?你知道吗
Article.objects
参见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)
参见https://docs.djangoproject.com/en/dev/topics/db/aggregation/#aggregating-annotations中的示例:
您需要annotate您的queryset为每篇文章设置注释的数量,然后在注释字段上进行筛选。你知道吗
相关问题 更多 >
编程相关推荐