Amandasaurus
Amandasaurus

Reputation: 60799

Effecient way to create 2 django objects that link to each other with a ForeignKey?

This seems like a simple question, but I feel like I'm missing something.

I have 2 objects: A, and B. B has a ForeignKey to A called my_a, and for various reasons I need to have a ForeignKey on A to B, i.e. A.the_b_used. In a view function I want to create an instance of A (a = A()), and an instance of B (b = B()), and to then link them together. However my objects (a & b) need to have ids before I can link them (right?), so I think you have to do this:

a = A()
b = B()
a.save()
b.save()
a.the_b_used = b
b.my_a = a
a.save()
b.save()

It looks like I have to do 4 .save()'s, i.e. 4 write database operations. Is there a way to do this without having to do as many database opertions? I might be missing something simple.

Upvotes: 0

Views: 103

Answers (1)

SingleNegationElimination
SingleNegationElimination

Reputation: 156278

In most cases, you shouldn't need to have a foriegn key from a parent object to a child object if there's already a foreign key from the child back to the parent. A One-to-one correspondence is achieved by making the foreign key column on the child object unique, so that only one child can link to a particular parent.

Supposing you did exactly this with 'A' as the child, having a foreign key column to parent 'B'. Since the link from b back to a is implicit from the link from a to b, you don't need to know a's id for b to be complete.

a = A()
b = B()
b.save()

b has an 'id', which we can use with for a

a.the_b_used = b
a.save()

That's all you should need.

Upvotes: 1

Related Questions