如何修复多个注释总和给出错误的答案

时间:2019-04-24 09:30:59

标签: python django django-models django-orm

我想注释该组中的observation_taken计数和observation_given计数。

型号:-

class Observation(TimeStampedEnumeratedUUIDModel):
rubric = models.ForeignKey('rubrics.Rubric', related_name='observations')
gro`enter code here`up = models.ForeignKey(
    'access.Group', related_name='group_observations')
observer = models.ForeignKey(
    'access.UserRoleAccount', related_name='user_observations_taken')
observee = models.ForeignKey(
    'access.UserRoleAccount', related_name='user_observations_given')
is_published = models.BooleanField(default=False)

class UserRoleAccount(TimeStampedUUIDModel):
user = models.OneToOneField(User, related_name="user_role_account")
role = models.ForeignKey(Role, related_name="user_role_account")
account = models.ForeignKey(Account, related_name="user_role_account")

multiple annotate Sum terms yields inflated answer

UserRoleAccount.objects.filter(pk='24f4a032-3f83-4123-8330fa60fcbb880c').annotate(count=Sum(Case(When(user_observations_taken__group=grp,then=1)),default=0,output_field=IntegerField(),distinct=True)).annotate(count1=Sum(Case(When(user_observations_given__group=grp,then=1)),default=0,output_field=IntegerField(),distinct=True)) 

1 个答案:

答案 0 :(得分:0)

我找到了适合我的解决方案。

ura = UserRoleAccount.objects.filter(pk='24f4a032-3f83-4123-8330-fa60fcbb880c'). annotate(taken_count=Count(Case(When(user_observations_given__group=grp,then='user_observations_given')),distinct=True)). annotate(given_count=Count(Case(When(user_observations_taken__group=grp,then='user_observations_taken')),distinct=True))