我有这种情况
class Video(models.Model):
public = models.BooleanField()
parent = models.ForeignKey('self', related_name='children')
我想获得一个按公众所拥有的孩子数量排序的视频列表。
我可以做类似的事情:
video.objects.annotate(children_count=Count('children')).order_by('children_count')
按照孩子数量的顺序给我一组视频 - 但这对私人和公共儿童都有影响。我如何只计算公共儿童?
我想要这样的事情:
video.objects.annotate(children_count=Count('children' where children.public=True)).order_by('children_count')
当然不能正常工作
答案 0 :(得分:0)
怎么样
Video.objects.filter(public=True).
annotate(children_count=Count('children')).order_by('children_count')
在此处详细了解:https://docs.djangoproject.com/en/dev/topics/db/aggregation/#aggregations-and-other-queryset-clauses
答案 1 :(得分:0)
有效的是:
Video.objects.filter(children__public =真).annotate(children_count =计数( '孩子'))。ORDER_BY( 'children_count')