【问题标题】:How to fix multiple annotate Sum give wrong answer如何修复多个注释总和给出错误答案
【发布时间】:2019-09-13 13:25:54
【问题描述】:

我想在该组中注释observation_taken count 和observation_given count。

型号:-

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)) 

【问题讨论】:

    标签: python django django-models django-orm


    【解决方案1】:

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

    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))

    【讨论】:

      猜你喜欢
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2013-03-01
      • 2023-03-14
      • 2014-11-19
      • 2020-02-16
      • 1970-01-01
      相关资源
      最近更新 更多