#33682: SQL generation bug in `.distinct()` when supplied fields go through
multiple many-related tables
-------------------------------------+-------------------------------------
Reporter: Robert Leach | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: 3.2
(models, ORM) |
Severity: Normal | Resolution:
Keywords: sql, distinct, | Triage Stage:
| Unreviewed
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by Robert Leach):
I believe that the note at the bottom of the distinct section of this doc:
[https://docs.djangoproject.com/en/4.0/ref/models/querysets/#distinct]
answers my above question, but to dissect the verbiage it tells you *what*
to do without the *why* fully described. It tells you that adding the
`_id` field would be necessary to **make the expressions match** (which is
"a" reason why to add the `id` field), but it doesn't explicitly explain
why that makes them match, or say whether the `id` field is precisely
required or if any field will do.
If I'd better understood the *why* in that doc, I might have coded the
right solution to the gotcha and not overlooked the other cases.
My updated understanding is that it seems that the reason *a* related
model field is necessary is because the related model "field" in the model
definition that links to the related model isn't a "field". It's a
reference that gets turned into a field that by default uses the
`meta.ordering`. (I didn't even notice that the distinct clause had
`compound_id` and the order by clause had `name` in that position.) So
I'm guessing that *any*(?) related model field in front of a (non-field)
related model reference (whether it's at the beginning of the distinct
list or "just before" the non-field related model reference) would solve
the issue? Or will *any* explicit inclusion of a non-field related model
reference cause the problem? **Or** perhaps even explicit inclusion of
such a (non) field would cause the problem.
I think these are areas in which the doc could be improved just a bit
more. Understanding the /why/ **better**, I think, could be helpful to
avoid these pitfals, and also help to understand an otherwise cryptic
error message.
--
Ticket URL: <https://code.djangoproject.com/ticket/33682#comment:3>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/010701809a2375a7-2fa0c291-d8a3-429a-8dbe-a18ca44cd1d4-000000%40eu-central-1.amazonses.com.