Opened 4 years ago

Closed 4 years ago

#31285 closed Bug (fixed)

Inherited model doesn't correctly order by "-pk" when specified on Parent.Meta.ordering

Reported by: Jon Dufresne Owned by: Jon Dufresne
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Given the following model definition:

from django.db import models

class Parent(models.Model):
    class Meta:
        ordering = ["-pk"]

class Child(Parent):
    pass

Querying the Child class results in the following:

>>> print(Child.objects.all().query)
SELECT "myapp_parent"."id", "myapp_child"."parent_ptr_id" FROM "myapp_child" INNER JOIN "myapp_parent" ON ("myapp_child"."parent_ptr_id" = "myapp_parent"."id") ORDER BY "myapp_parent"."id" ASC

The query is ordered ASC but I expect the order to be DESC.

Change History (5)

comment:1 by Simon Charette, 4 years ago

Triage Stage: UnreviewedAccepted

Interesting ordering is effectively one of the rare Meta attribute preserved during MTI inheritance.

I also wonder if ordering = ('pk',) should be special cased to order by the local child class primary key which would be "myapp_child"."parent_ptr_id" in this case since it should result in the same resulset because of foreign key integrity and avoid an unnecessary JOIN in the cases where no parent fields are involved.

in reply to:  1 comment:2 by Jon Dufresne, 4 years ago

Has patch: set

https://github.com/django/django/pull/12470

I also wonder if ordering = ('pk',) should be special cased to order by the local child class primary key which would be "myapp_child"."parent_ptr_id" in this case since it should result in the same resulset because of foreign key integrity and avoid an unnecessary JOIN in the cases where no parent fields are involved.

Interesting enough, ordering by ["-id"] was already doing that. So I agree that "-pk" should behave the same.

comment:3 by Simon Charette, 4 years ago

I would expect Parent.meta.ordering = ["id"] to result in ORDER BY "myapp_parent"."id" while Parent.meta.ordering = ["pk"] results in ORDER BY "myapp_child"."parent_ptr_id".

Isn't that the case right now?

comment:4 by Abhijeet Viswa, 4 years ago

Owner: changed from nobody to Jon Dufresne
Status: newassigned

I'm changing the owner and status since there already is a patch by the reporter.

comment:5 by Mariusz Felisiak <felisiak.mariusz@…>, 4 years ago

Resolution: fixed
Status: assignedclosed

In 013147fa:

Fixed #31285 -- Fixed inherited Meta.ordering of "-pk".

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