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👍
OneToOneField
s 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.
- [Django]-How to catch A 'UNIQUE constraint failed' 404 in django
- [Django]-Django 2.0 path error ?: (2_0.W001) has a route that contains '(?P<', begins with a '^', or ends with a '$'
- [Django]-Circular dependency in serializers
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.
- [Django]-Max image size on file upload
- [Django]-Django log rotating and log file ownership
- [Django]-Handlebars.js in Django templates