One-to-One Relationships

One-to-One Relationships

One-to-one relationships are often used when two models share a unique relationship. For example, let’s say we have a Profile model associated with a User model. Each user should have exactly one profile, and each profile belongs to a single user. In Django, you can define a one-to-one relationship using the OneToOneField:

from django.db import models
from django.contrib.auth.models import User


class Profile(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
  bio = models.TextField()
  website = models.URLField()

Last updated