在python django中生成错误的group_by查询

时间:2015-12-01 14:52:33

标签: python django group-by django-queryset

我正在使用Django == 1.8.7,我有以下模型

# a model in users.py
class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=100, blank=True)
    displayname = models.CharField(max_length=100, blank=True)
    # other fields deleted

# a model in healthrepo.py
class Report(models.Model):
    id = models.AutoField(primary_key=True)
    uploaded_by = models.ForeignKey(User, related_name='uploads',
                                    db_index=True)
    owner = models.ForeignKey(User, related_name='reports', db_index=True)
    # other fields like dateofreport, deleted

我使用以下Django查询集:

Report.objects.filter(owner__id=1).values('uploaded_by__username',
                                          'uploaded_by__displayname').annotate(
                                              total=Count('uploaded_by__username')
                                          )

我看到这会生成以下查询:

SELECT T3."username", T3."displayname", COUNT(T3."username") AS "total" FROM "healthrepo_report"
INNER JOIN "users_user" T3 ON ( "healthrepo_report"."uploaded_by_id" = T3."id" )
WHERE "healthrepo_report”.”owner_id" = 1
GROUP BY T3."username", T3."displayname", "healthrepo_report"."dateofreport", "healthrepo_report”.”owner_id", "healthrepo_report"."uploaded_by_id"
ORDER BY "healthrepo_report"."dateofreport" DESC, "healthrepo_report"."user_id" ASC, "healthrepo_report"."uploaded_by_id" ASC

然而,我真正想要的只是基于“healthrepo_report”。“owner_id”而不是多个字段进行分组。即我想要的是:

SELECT T3."username", T3."displayname", COUNT(T3."username") AS "total" FROM "healthrepo_report"
INNER JOIN "users_user" T3 ON ( "healthrepo_report"."uploaded_by_id" = T3."id" )
WHERE "healthrepo_report”.”owner_id" = 1
GROUP BY T3."username", T3."displayname" ORDER BY "healthrepo_report"."dateofreport" DESC, "healthrepo_report"."user_id" ASC, "healthrepo_report"."uploaded_by_id" ASC

我想知道为什么会这样,我如何根据单列进行分组。

1 个答案:

答案 0 :(得分:0)

我刚刚看到这篇文章:

Django annotate and values(): extra field in 'group by' causes unexpected results

通过添加空order_by()来更改查询

Report.objects.filter(owner__id=1).values('uploaded_by__username',
                                      'uploaded_by__displayname').annotate(
                                          total=Count('uploaded_by__username')
                                      ).order_by()