Relational fields in Django models (original) (raw)

Last Updated : 15 Jan, 2026

Django models often represent real-world entities that are connected to each other. To manage these connections, Django provides fields to define relationships between models. Relationships allow models to link and share data.

Django supports three main types of relationships:

1. Many-to-One fields

A many-to-one relationship is used when one record of a model is related to multiple records of another model.

**Example:

Python `

from django.db import models

class Album(models.Model): title = models.CharField(max_length = 100) artist = models.CharField(max_length = 100)

class Song(models.Model): title = models.CharField(max_length = 100) album = models.ForeignKey(Album, on_delete = models.CASCADE)

`

**In this example:

2. Many-to-Many fields

A many-to-many relationship is used when one record of a model is related to multiple records of another model and vice versa.

**Example:

Python `

from django.db import models

class Author(models.Model): name = models.CharField(max_length = 100) desc = models.TextField(max_length = 300)

class Book(models.Model): title = models.CharField(max_length = 100) desc = models.TextField(max_length = 300) authors = models.ManyToManyField(Author)

`

**In this example:

3. One-to-One fields

A one-to-one relationship is used when one record of a model is related to exactly one record of another model. This is useful when an object extends another object in some way.

**Example:

Python `

from django.db import models

class Vehicle(models.Model): reg_no = models.IntegerField() owner = models.CharField(max_length = 100)

class Car(models.Model): vehicle = models.OneToOneField(Vehicle, on_delete = models.CASCADE, primary_key = True) car_model = models.CharField(max_length = 100)

`

**In this example:

Data integrity options

When models depend on other models, it’s important to define what happens to related records when a record is deleted. This is controlled using the **on_delete parameter in relational fields.