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.