django - Is there any way around saving models that reference each other twice? -
my issue when saving new models need reference each other, not using related_name
lookup, such this:
class many: owner = models.foreignkey('one') class one: current = models.onetoonefield('many')
by default, these have null=false
and, please correct me if i'm wrong, using these impossible until change 1 of relationships:
current = models.onetoonefield('many', null=true)
the reason because can't assign model relationship unless saved. otherwise resulting in valueerror: 'cannot assign "<...>": "..." instance isn't saved in database.'
.
but when create pair of these objects need save twice:
many = many() 1 = one() one.save() many.owner = 1 many.save() one.current = many one.save()
is right way it, or there way around saving twice?
there no way around it, need save 1 of objects twice anyway.
this because, @ database level, need save object id. there no way tell sql database "save 2 objects , assign ids fields on other object". if manually, insert first object null fk, id back, insert second object id of first one, id back, update first object set fk. encapsulate whole thing in transaction.
so you're doing orm closest can get. may want add following on top of that:
1) use transaction changes, this:
from django.db import transaction transaction.atomic(): many, 1 = many(), one() one.save() many.owner = 1 many.save() one.current = many one.save(update_fields=['current']) # slight optimization here
2) encapsulated in transaction, want remove null=true
. but cannot, are, unfortunately, checked immediately. [edit: appears oracle might support deferring not null check, if you're using oracle can try dropping null=true
, should work.]
you'll want check how code reacts if @ later point, when reading db, if reason (manual editing, bugged insert somewhere, ...) one.current.owner != one
.
Comments
Post a Comment