Opened 3 weeks ago
Last modified 3 weeks ago
#37246 assigned Cleanup/optimization
"Database Representation" section of Relationship Fields reference should clarify it is not referring to the `_id` syntax for foreign key values
| Reported by: | Jakub Nowak | Owned by: | maheen8q |
|---|---|---|---|
| Component: | Documentation | Version: | 6.0 |
| Severity: | Normal | Keywords: | |
| Cc: | Jakub Nowak | Triage Stage: | Accepted |
| Has patch: | yes | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
https://docs.djangoproject.com/en/6.1/ref/models/fields/#database-representation
The documentation says that one should never use _id fields. Unfortunately writing comparison as author.book_id == book.pk is better than author.book == book, because the latter causes author.book foreign object to be fetched from the database.
We could improve that by making it so that author.book.pk returns author.book_id without fetching author.book foreign object from the database.
Change History (7)
comment:1 by , 3 weeks ago
| Component: | Database layer (models, ORM) → Documentation |
|---|---|
| Summary: | Accessing `pk` field of a foreign object should not fetch object from the database → "Database Representation" section of Relationship Fields reference should clarify it is not referring to the `_id` syntax for foreign key values |
| Triage Stage: | Unreviewed → Accepted |
comment:2 by , 3 weeks ago
Do you think that change might have some negative side-effects? Profiling random open-source projects might be a good idea to check if it doesn't degrade performance. How about considering it for the next major release?
comment:3 by , 3 weeks ago
It would be backward incompatible, and without knowing the mechanism to accomplish it, could violate a lot of developers' mental models about how model materialization works.
comment:4 by , 3 weeks ago
| Has patch: | set |
|---|---|
| Owner: | set to |
| Status: | new → assigned |
comment:5 by , 3 weeks ago
| Has patch: | unset |
|---|
comment:6 by , 3 weeks ago
| Has patch: | set |
|---|
Hi, thanks for the ticket.
I don't think that documentation section means to say to not use
_idto access pk's. In fact, we advise doing exactly that elsewhere:https://docs.djangoproject.com/en/dev/topics/db/optimization/#use-foreign-key-values-directly
Rather, I think it is preventing a misunderstanding that changing db column names will have some effect on the Python code you write. I think this section could be clearer. I'm accepting this as a documentation ticket to prevent the misinterpretation of this advice to mean "don't use _id to access foreign key values directly".
In terms of
author.book.pknot materializingauthor.book, I don't think we would consider such a large change to the ORM like that.