Assigning a Model Instance to a Foreign Key Attribute Doesn't Cache the Instance
|Reported by:||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 9 years ago by
|Owner:||changed from nobody to Philippe Raoult|
|Triage Stage:||Unreviewed → Accepted|
comment:2 Changed 9 years ago by
|Owner:||changed from Philippe Raoult to Jacob|
|Status:||new → assigned|