Django ORM计数相关字段

时间:2017-12-20 14:03:18

标签: python django django-models orm django-orm

我有以下型号:

class Profile(models.Model):
    pass

class Team(models.Model):
    ...
    members = models.ManyToManyField("main.Profile", through='main.TeamMember')

class TeamMember(models.Model):
    profile = models.ForeignKey('Profile')
    team = models.ForeignKey('Team')
    role = models.CharField(max_length=255)

所以,我尝试通过计算具有特定角色的个人资料来订购团队,并且我有一个查询,这不起作用:

Team.objects.filter(members__role='ExampleRole').annotate(example_role_count=Count('members')).order_by('example_role_count')

它引发了以下异常:

django.core.exceptions.FieldError: Related Field got invalid lookup: role

因为role是TeamMember字段,而不是Profile。那么,我如何通过具有指定角色的成员数来实现排序?

2 个答案:

答案 0 :(得分:0)

最后,找到了一个解决方案(仅适用于Django> = 1.11)

queryset = Team.objects.annotate(example_role_count=Subquery(TeamMember.objects.filter(role='example_role', team=OuterRef('pk')).values('team').annotate(cnt=Count('pk')).values('cnt'), output_field=IntegerField())).order_by('-example_role_count')

答案 1 :(得分:0)

如果您想通过'来过滤查询集。模型字段,然后想要根据相关字段计数来排序结果集,

from django.db.models import Count

# descending order
Team.objects.filter(teammember__role='ExampleRole').annotate(example_role_count=Count('members')).order_by('-example_role_count')