Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django OneToOneField - in which model should I put it?

Let's assume that we have the following models.

class A(Model): pass
class B(Model): pass

Then there is no difference between:

In model A: b = OneToOneField(B, related_name=A.__name__)

and

in model B: a = OneToOneField(A, related_name=B.__name__)

So what questions should I ask myself to decide whether to put OTO in one model or another. I mean like has-a, is-a and so on.

like image 252
aemdy Avatar asked Mar 21 '12 07:03

aemdy


2 Answers

There actually is a difference in where you put the one-to-one field, because deletion behaves differently. When you delete an object, any other objects that had one-to-one relationships referencing that object will be deleted. If instead you delete an object that contains a one-to-one field (i.e. it references other objects, but other objects are not referencing back to it), no other objects are deleted.

For example:

class A(models.Model):
    pass

class B(models.Model):
    a = models.OneToOneField(A)

If you delete A, by default B will be deleted as well (though you can override this by modifying the on_delete argument on the OneToOneField just like with ForeignKey). Deleting B will not delete A (though you can change this behavior by overriding the delete() method on B).

Getting back to your initial question of has-a vs. is-a, if A has a B, B should have the one-to-one field (B should only exist if A exists, but A can exist without B).

like image 80
Erin Heyming Avatar answered Oct 04 '22 20:10

Erin Heyming


OneToOneFields are really only for two purposes: 1) inheritance (Django uses these for its implementation of MTI) or 2) extension of a uneditable model (like creating a UserProfile for User).

In those two scenarios, it's obvious which model the OneToOneField goes on. In the case of inheritance, it goes on the child. In the case of extension it goes on the only model you have access to.

With very few exceptions, any other use of a one-to-one should really just be merged into one single model.

like image 24
Chris Pratt Avatar answered Oct 04 '22 21:10

Chris Pratt