Assume A
and B
are django Models, where A
has a foreign key field to B
:
a = A()
b = B()
a.my_b = b
b.save()
a.save()
Surprisingly a
is saved with null
in the my_b
foreign key field. If you check a.my_b
before or after the saves it does refer to the b
instance, however it seems that django evaluates the foreign key id itself upon a.my_b = b
assignment and not upon a.save()
. In complex systems and flows it may be hard to change the order of commands, so simply saving b
before assigning it to a
could be impractical...
Adding the incredible statement a.my_b=a.my_b
between the save commands works, but seems to me a horrid workaround.
Is there a way to configure django to re-evaluate foreign keys upon saving model instances?
Is there a different approach that might solve this issue?