Opened 10 years ago

Last modified 10 years ago

#23774 closed Cleanup/optimization

Documentation on ordering by ForeignKey fields is misleading — at Version 1

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 (last modified by David Wolever)

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 misleading, and should probably show ordering by the related model's ordering.

A quick example that might be more instructive::

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

Edit I can't read and totally missed the "or order by the related model’s primary key if there is no Meta.ordering specified" each time I read the documentation. I'll leave the ticket standing as I'm probably not the only one to hit this?

Change History (2)

comment:1 by David Wolever, 10 years ago

Description: modified (diff)
Summary: Documentation on ordering by ForeignKey fields is incorrectDocumentation on ordering by ForeignKey fields is misleading

by Tim Graham, 10 years ago

Attachment: 23774.diff added
Note: See TracTickets for help on using tickets.
Back to Top