Full answer
Use a OneToOneField for extension data such as a StudentProfile attached to a user, or to split a very wide table.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")Forward access: profile.user. Reverse access: user.profile, a single object, not a manager. If no profile exists, Django raises User.profile.RelatedObjectDoesNotExist (a subclass of AttributeError and DoesNotExist), so use hasattr(user, "profile") or catch it.
ForeignKey reverse access is a manager: class_room.student_set.all() by default. Setting related_name="students" renames it to class_room.students.all() and also the query name: ClassRoom.objects.filter(students__name="Asha") (use related_query_name to change only the query name).
Rules:
- Two foreign keys from one model to the same target (for example
created_byandreviewed_by) clash on the default reverse name, so give each a distinctrelated_name. The system check fails otherwise (fields.E304). related_name="+"disables the reverse accessor.- For queries,
select_related("profile")follows one-to-one in either direction in a single JOIN, which avoids an extra query per row.
Pick related_name as a plural noun for ForeignKey (students) and a singular noun for OneToOne (profile) so the code reads naturally.
import sys
import types
import django
from django.conf import settings
# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__
settings.configure(
SECRET_KEY="demo-only-key-not-for-production",
ALLOWED_HOSTS=["testserver"], # the host name used by Django's test client
INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()
from django.db import models, connection
class ClassRoom(models.Model):
name = models.CharField(max_length=10)
class Meta:
app_label = "school"
class Student(models.Model):
name = models.CharField(max_length=40)
class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE, related_name="students")
class Meta:
app_label = "school"
class Profile(models.Model):
student = models.OneToOneField(Student, on_delete=models.CASCADE, related_name="profile")
bio = models.CharField(max_length=80)
class Meta:
app_label = "school"
with connection.schema_editor() as editor:
for m in (ClassRoom, Student, Profile):
editor.create_model(m)
room = ClassRoom.objects.create(name="10A")
asha = Student.objects.create(name="Asha", class_room=room)
ravi = Student.objects.create(name="Ravi", class_room=room)
Profile.objects.create(student=asha, bio="Loves maths")
print([s.name for s in room.students.all()]) # reverse ForeignKey: a manager
print(asha.profile.bio) # reverse OneToOne: an object
try:
ravi.profile
except Profile.DoesNotExist as exc:
print("no profile:", type(exc).__name__)
print(ClassRoom.objects.filter(students__name="Ravi").count())
print(Student.objects.select_related("profile").get(name="Asha").profile.bio)
Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): ['Asha', 'Ravi'] Loves maths no profile: RelatedObjectDoesNotExist 1 Loves maths
Key points
- OneToOne is a unique ForeignKey
- Reverse of ForeignKey is a manager; reverse of OneToOne is an object
- related_name renames the reverse accessor and the query name
- Two FKs to the same model need distinct related_name values
- select_related follows one-to-one in a single query
Common mistakes
- Expecting a reverse OneToOne to return None instead of raising
- Using the same default reverse name for two ForeignKeys to one model
- Accessing reverse relations in a loop without select_related
- Forgetting that related_name also changes the filter keyword
Follow-ups
- How does Django name the reverse accessor if you omit related_name?
- How would you attach optional profile data to the built-in User?
- What does on_delete=PROTECT do on the OneToOne side?
Tips
- Separate manager vs object in the reverse direction
- Mention the error for missing reverse object
- Show select_related