Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: assigning foreign key before target model is saved

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?

like image 581
Jonathan Livni Avatar asked Nov 06 '12 10:11

Jonathan Livni


1 Answers

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.

like image 160
Alasdair Avatar answered Sep 28 '22 03:09

Alasdair