[Fixed]-Difference between django's OneToOneField and django's OneToOneRel


OneToOneRel is an internal class which implements the back reference of a one to one relationship. It is not documented anywhere, not part of any public api, and is not for use in your app.


First I thought, there is no ‘OneToOneRel’. But there is. It’s not in the documentation. But it lives in the Django source code. So there is the first difference. 😉

I decided to look up the OneToOneField in the Django source. This is the docstring for the OneToOneField:

A OneToOneField is essentially the same as a ForeignKey, with the
exception that always carries a “unique” constraint with it and the
reverse relation always returns the object pointed to (since there
will only ever be one), rather than returning a list.

But we allready knew that. Cool thing is, a few lines down you see:

rel_class = OneToOneRel

So the second difference is that OneToOneRel is used in OneToOneField.

Than I searched for OneToOneRel in this Python file and found:

class OneToOneRel(ManyToOneRel):

So the third difference is that OneToOneRel is a subclass of ManyToOneRel but OneToOneField is a subclass of ForeignKey.

For me this is enough to know: OneToOneRel is used in a OneToOneField. OneToOneRel is what a ManyToOneRel is for a ForeignKey and a ManyToManyRel for a ManyToManyField. Those rel classes seem to handle constraints.

The important part: You can’t compare OneToOneField with OneToOneRel in the same way you can compare OneToOneField with ForeignKey because OneToOneRel is not a relationship field.

Leave a comment