Home > OS >  Django OneToOne fields conflicting when creating both instances in same view
Django OneToOne fields conflicting when creating both instances in same view

Time:11-19

I'm sure I'm missing something here.

I do have two models, Foo and Bar like so

class Foo(models.Model):
   bar = models.OneToOneField(Bar)
   ..


class Bar(models.Model):
   foo = models.OneToOneField(Foo)
   ..

Now I have to create new instances for both of them which will be mapped 1-1. Creating an instance, it requires me to map name to the other instance which doesn't exist yet.

How to handle with this? Is there a way to create an empty instance beforehand or s.th.?

foo_instance = Foo(bar=bar_instance)
foo_instance.save()


# won't work since bar_instance not yet created
..

CodePudding user response:

You should declare relationship only one time.

class Foo(models.Model):
   ..


class Bar(models.Model):
   foo = models.OneToOneField(Foo)
   ..

Then, you call your objects in both sides of the instances.

foo_instance = Foo()

bar_instance = Bar(foo=foo.instance)

bar_instance.foo
foo_instance.bar # As the name of the class, but in lowercase

Here the docs

  • Related