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?
There's a Django ticket that describes this issue, #8892.
In the meantime, there's no configuration setting that changes the behaviour. You'll have to change the order of your save and assignment operations, or do the extra assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With