Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Django OneToOne fields conflicting when creating both instances in same view

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
..
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!