Assigning a Model Instance to a Foreign Key Attribute Doesn't Cache the Instance
|Reported by:||Andy McCurdy <sedrik@…>||Owned by:||jacob|
|Component:||Database layer (models, ORM)||Version:||master|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Currently, when assigning a model instance to a forkeign key attribute doesn't cache the model instance being assigned. Rather, it simply deletes the prior cached attribute.
This causes two undesired behaviors:
- If code later in the execution process references the FK attribute rather than the model instance, a sql query is run to fetch the result, because it's not cached.
- It makes race conditions easy in post-save signals, where in many cases it's easy to end up with multiple instances of the same object.
Oddly enough, it seems GenericForeignKey gets this right. On line# 92 of django/contrib/contenttypes/generic.py, the instance being assigned gets cached on the model. However, on line# 225 of django/db/models/fields/related.py, the cached attribute simple gets deleted.
I believe line# 225 should be changed to save the instance being assigned on the cached attribute.
Change History (6)
comment:1 Changed 7 years ago by PhiR
- Needs documentation unset
- Needs tests unset
- Owner changed from nobody to PhiR
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
comment:2 Changed 7 years ago by jacob
- Owner changed from PhiR to jacob
- Status changed from new to assigned
Changed 7 years ago by jacob
comment:4 Changed 7 years ago by jacob
- Resolution set to fixed
- Status changed from assigned to closed