Sov*_*iut 5 django django-models django-queryset django-managers generic-relationship
我正在使用object_list通用视图来快速列出一组文章.每篇文章都附有评论.该查询使用注释Count()数量的注释,然后order_by()使用注释的数字.
'queryset': Article.objects.annotate(comment_count=Count('comments')).order_by('-comment_count'),
Run Code Online (Sandbox Code Playgroud)
注释是django.contrib.comments框架的一部分,并通过通用关系附加到模型.我在我的文章模型中添加了显式反向查找:
class Article(models.Models):
...
comments = generic.GenericRelation(Comment, content_type_field='content_type', object_id_field='object_pk')
Run Code Online (Sandbox Code Playgroud)
问题是,这会计入"不活跃"的评论; 那些有is_public=False或is_removed=True.如何排除任何不活动的评论?
聚合文档解释了如何执行此操作。您需要使用一个filter子句,确保将其放在子句之后annotate:
Article.objects.annotate(comment_count=Count('comments')).filter(
comment__is_public=True, comment__is_removed=False
).order_by('-comment_count')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
531 次 |
| 最近记录: |