Opened 13 years ago
Closed 13 years ago
#18275 closed Uncategorized (wontfix)
documentation: invalid foreign key and select_related
Reported by: | Owned by: | nobody | |
---|---|---|---|
Component: | Documentation | Version: | 1.3 |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | yes | UI/UX: | no |
Description
Let's say Book has a foreign key to Author.
If there is a invalid id in the Author field of any Book instance, then these two queries get a different set
of Book instances:
Book.objects.all()
Book.objects.select_related('author').all()
The second query will omit the Book objects that have an author field that points nowhere.
This surprised me since I thought of select_related as only ADDING information to a query. In this situation it also REMOVES information.
Invalid keys can happen with a database that does not have referential integrity checking like mysql with MyISAM.
I'm going to WONTIFX this - there are probably any number of bugs that will be caused by a corrupt database. The model layer assumes your Model class reflects your database correctly, and if you've used a foreign key when its possible for the data to not be a foreign key, your model is incorrect. This is similar to bugs that would occur if you've got an incorrect max_length on
CharField
. Either your database needs to have referential integrity or your business logic needs to ensure integrity.