简体   繁体   中英

Erroneous group_by query generated in python django

I am using Django==1.8.7 and I have the following models

# 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

I use the following Django queryset:

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

I see that this generates the following query:

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

However, what I really wanted was just grouping based on "healthrepo_report”.”owner_id" and not multiple fields. ie What I wanted was:

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

I am wondering why this is happening and how do I get grouping based on single column.

I just saw this post:

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

Changing the query by adding empty order_by() fixes it

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM