liveBook · Manning

OneToOneField

As explained in Django in Action

OneToOneField is a Django model field that creates a one-to-one relationship, so each object on either side relates to at most one object on the other side.

A OneToOneField creates a one-to-one database relationship: each object can relate to at most one object on the other side. It is especially useful for attaching custom profile data to Django’s User account. section 6.2.1

Use a OneToOneField when a single related object must match a single account or record:

  • Store musician-specific data in a separate profile model linked to one User object. section 6.2.1
  • Apply the same relationship restriction outside user profiles whenever a database foreign key must allow only one related object. section 6.2.1
  • Choose the profile approach early when keeping Django’s User credentials, because switching later can require custom migrations and data cleanup. section 6.2.1

A musician profile

A Musician ORM object can hold custom musician data while a separate profile object connects it to one Django User account. The User supplies account and credential behavior; the profile supplies application-specific fields. section 6.2.1

Figure 6.2 User profiles vs. replacing the User ORM object for user data storage
figure

Compare storing custom fields in a profile linked with OneToOneField against replacing Django’s User object entirely. section 6.2.1

How Django in Action covers it

How deep it goes
Defines the one-to-one constraint and contrasts profile storage with replacing User, but does not detail field syntax.
Examples
Uses a musician account and profile object to demonstrate storing custom data alongside a User object.
What you can do after
Apply it via Django to associate one profile or related record with exactly one User or other model object.
How it connects
Connects user profiles, the Django User model, custom user models, database foreign keys, authentication, and signals.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Django in Action. The section links point to the parts of the book it draws on.