[Django]-Django OneToOneField – in which model should I put it?

46👍

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

10👍

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.

0👍

By the way, I needed OneToOneField to prevent circular dependency (inheritance use):

Model A:
  ...
  current_choice = models.ForeignKey(B)

Model B:
  ...
  parent = models.ForeignKey(A)

That means, A needs B to be defined. Not a good database convention for bootstrapping.
Instead I did:

Model A:
  ...

Model B:
  ...
  parent = models.ForeignKey(A)

Model C:
  parent = models.OneToOneField(A)
  current_choice = models.ForeignKey(B)

With respect to example from documentation, you can also have clean queries like: p1.restaurant.place.restaurant.place… This is madness.

Leave a comment