Django OneToOneField - in which model should I put it? Django OneToOneField - in which model should I put it? django django

Django OneToOneField - in which model should I put it?


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):    passclass 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).


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.


I think the case of a OneToOne field, the correct answer is that it doesn't matter, it just depends on which model it makes more sense to relate to the other.