Opened 2 years ago

Closed 2 years ago

#34005 closed Bug (invalid)

In Django 3.2 the ORM looses Meta.ordering default order when .annotate is used

Reported by: Pieter Zieschang Owned by: nobody
Component: Database layer (models, ORM) Version: 3.2
Severity: Normal Keywords: orm Meta Options.ordering annotate
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Pieter Zieschang)

Hi,
I've upgraded from 2.2 to 3.2.15 and now default ordering specified in the Model does not work anymore if i annotate the QuerySet.
I suspect this is a ORM Bug, as the ordering / default order is not in the query anymore since the update to 3.2.

Product class:

class Product(models.Model):
...
    class Meta:
        ordering = ["name"]

Default ordering is working nicely without annotate ... see ORDER BY

>>> print(Product.objects.all().select_related("category").query)
SELECT "memberapp_product"."id",  [...] FROM "memberapp_product" INNER JOIN "memberapp_productcategory" ON ("memberapp_product"."category_id" = "memberapp_productcategory"."id")  ORDER BY "memberapp_product"."name" ASC 

but not anymore when annotate (with a special sum) is used - no ORDER BY anymore in the query:

>>> print(Product.objects.all().select_related("category").annotate(**kwargs).query)
SELECT "memberapp_product"."id", [...]  LEFT OUTER JOIN "memberapp_appointment" ON ("memberapp_appointmentattendee"."appointment_id" = "memberapp_appointment"."id") INNER JOIN "memberapp_productcategory" ON ("memberapp_product"."category_id" = "memberapp_productcategory"."id") GROUP BY "memberapp_product"."id", "memberapp_productcategory"."id"

Since it's been working before i would expect something in the ORM looses the order by in complex queries using annotate.

Thanks for looking into this.

Change History (2)

comment:1 by Pieter Zieschang, 2 years ago

Description: modified (diff)

comment:2 by Tim Graham, 2 years ago

Resolution: invalid
Status: newclosed

Model Meta.ordering affecting GROUP BY queries was deprecated in Django 2.2 and removed in Django 3.1.

Note: See TracTickets for help on using tickets.
Back to Top