Django Model Field Type: OneToOneField

By: Dusty Arlia
Published on Friday, April 4, 2014, 12:54 PM
Last Updated on Tuesday, July 14, 2015 at 1:44 AM
Total Updates: 3

The OneToOneField is a Django Model field type. These fields define one-to-one relationships. To use a OneToOneField, include it as a class attribute of your model. Here is an example:

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

The resulting Person model will have the following attributes:

>>> person = Person.objects.get(pk=1)
>>> hasattr(person, 'specialuser')
True
>>> hasattr(user, 'relative_of')
True

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

Comments:

Ad:

Ad: