Opened 6 years ago
Closed 6 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)
follow-up: 2 comment:1 by , 6 years ago
| Triage Stage: | Unreviewed → Accepted |
|---|
comment:2 by , 6 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 unnecessaryJOINin 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 , 6 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 , 6 years ago
| Owner: | changed from to |
|---|---|
| Status: | new → assigned |
I'm changing the owner and status since there already is a patch by the reporter.
Interesting
orderingis effectively one of the rareMetaattribute 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 unnecessaryJOINin the cases where no parent fields are involved.