Opened 2 hours ago

Last modified 87 minutes ago

#37246 new 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:
Component: Documentation Version: 6.0
Severity: Normal Keywords:
Cc: Jakub Nowak Triage Stage: Accepted
Has patch: no 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 (1)

comment:1 by Jacob Walls, 87 minutes 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: UnreviewedAccepted

Hi, thanks for the ticket.

I don't think that documentation section means to say to not use _id to 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.pk not materializing author.book, I don't think we would consider such a large change to the ORM like that.

Note: See TracTickets for help on using tickets.
Back to Top