#23774 closed Cleanup/optimization (fixed)
Documentation on ordering by ForeignKey fields is misleading
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 )
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?
Attachments (1)
Change History (6)
comment:1 by , 10 years ago
Description: | modified (diff) |
---|---|
Summary: | Documentation on ordering by ForeignKey fields is incorrect → Documentation on ordering by ForeignKey fields is misleading |
by , 10 years ago
Attachment: | 23774.diff added |
---|
comment:2 by , 10 years ago
Has patch: | set |
---|---|
Triage Stage: | Unreviewed → Accepted |
Type: | Uncategorized → Cleanup/optimization |
comment:3 by , 10 years ago
Resolution: | → fixed |
---|---|
Status: | new → closed |
Does the attached patch add clarity?