Django Model Field Type: OneToOneField
from django.db import models from django.contrib.auth.models import Person class SpecialPerson(models.Model): person = models.OneToOneField(Person) relative = models.OneToOneField(Person, related_name='relative_of')
As you can tell, the
OneToOneField requires one positional argument: the class to which the model will be related. The
relative_of argument is optional. If it is not included, Django will use the lower-case name of the current model as the default value (see the example below).
Person model will have the following attributes:
>>> person = Person.objects.get(pk=1) >>> hasattr(person, 'specialuser') True >>> hasattr(user, 'relative_of') True
OneToOneFields, recursive relationships can be defined and references to currently undefined models can be made.
OneToOneField fields used to be made the primary key on a model automatically. This is no longer true, but you can still manually pass the
primary_key argument. So it is possible to have multiple fields of type
OneToOneField on a single model.