[Answered ]-Python Django Multiple Database Committing Objects with Foreign Key Relations

2👍

Django remembers which database the object was saved with, so each newMessageSegment is still affiliated with the preview database until you save it to default and it correctly disallows the cross-database FK assignment. This is untested, but it might work to assign to the underlying msg_id field instead:

newMessageSegment.msg_id = newMessage.id

Failing that, you could create a new copy of newMessageSegment rather than just creating a new reference to it. I think you could automate that by iterating over msgSegment._meta.fields, but I might be overlooking a subtlety of inheritance or something. And any many-to-many fields would be a pain.

Or, if you just want to hack it, edit the internal object tracking it. I wouldn’t generally recommend that but it’s going to be changed when you save anyway.

newMessageSegment._state.db = "default"
newMessageSegment.msg = newMessage
newMessageSegment.save(using="default")

Leave a comment