Opened 10 years ago

Last modified 10 years ago

#23774 closed Cleanup/optimization

Documentation on ordering by ForeignKey fields is incorrect — at Initial Version

Reported by: David Wolever Owned by: nobody
Component: Documentation Version: 1.7
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

From the most recent documentation (https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by):

If you try to order by a field that is a relation to another model, Django will use the default ordering on the related model (or order by the related model’s primary key if there is no Meta.ordering specified. For example:

Entry.objects.order_by('blog')

...is identical to:

Entry.objects.order_by('blogid')

...since the Blog model has no default ordering specified.

But this is incorrect.

When ordering by a ForeignKey, the related model's default ordering will be used. For example, consider:

class WidgetType(Model):
    id = AutoField(primary_key=True)
    label = CharField(max_length=16)
    class Meta:
        ordering = ["label"]

class Widget(Model):
    type = ForeignKey(WidgetType)

Trying to order Widget by type will produce:

>>> print Widget.objects.all().order_by("type").query
SELECT "django_testproj_widget"."id", "django_testproj_widget"."type_id"
FROM "django_testproj_widget"
INNER JOIN "django_testproj_widgettype" ON ( "django_testproj_widget"."type_id" = "django_testproj_widgettype"."id" )
ORDER BY "django_testproj_widgettype"."label" ASC
>>> django.VERSION
(1, 7, 1, 'final', 0)

Change History (0)

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