Opened 4 years ago
Closed 4 years ago
#33594 closed Bug (needsinfo)
order_by("field1__-field2") yields inconsistent behavior
| Reported by: | Thomas C | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 3.2 |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description (last modified by )
In our codebase, someone used SomeModel.objects.order_by("foo__-created_at") to order according to a foreign key's field and it was working (yielding the correct query with DESC order).
However, after we added the following index on Foo:
class Meta:
indexes = [
models.Index(fields=["some_other_field", "-created_at"]),
]
The same code SomeModel.objects.order_by("foo__-created_at") stopped working and started raising an error:
django.core.exceptions.FieldError: Cannot resolve keyword '-created_at' into field. Choices are: context, created_at, id, tag_readings, updated_at, user_id, warehouse_id
Shouldn't the pattern for ordering in a descending order with chaining be documented?
According to https://github.com/django/django/blob/main/django/db/models/sql/compiler.py#L402-L403 it should be -foo__created_at.
Also, we should expect the wrong pattern to fail unconditionally.
Change History (4)
comment:1 by , 4 years ago
| Description: | modified (diff) |
|---|
comment:2 by , 4 years ago
comment:3 by , 4 years ago
| Description: | modified (diff) |
|---|
comment:4 by , 4 years ago
| Resolution: | → needsinfo |
|---|---|
| Status: | new → closed |
Thanks for updates, however I cannot reproduce FieldError after adding an index in Meta.indexes for Foo. Please provide a sample project that reproduces this issue. Can you reproduce on Django 4.0? or the current main branch?
"foo__-created_at"it's not intended, documented, or officially supported. It works by coincidence. I also cannot reproduceFieldErrorafter adding an index inMeta.indexes, I'm nor sure how adding an index can interrupt ordering 🤔. There is something wrong in the described models. Oncecreated_byis a field onSomeModeland once onfoo. Can you double-check and provide a reproducible scenario?