Last Updated : 12 Jul, 2025
Prerequisite: Django models, Relational fields in Django
In Django, a many-to-many relationship is used when instances of one model can be associated with multiple instances of another model and vice versa. For example, in a shop management system:
To model this, Django offers the ManyToManyField. However, there are cases where you want to store additional information about the relationship itself, such as:
In such cases, you need an intermediate model (also called a through model) to store this extra data.
Example of ManyToManyField Model Step 1. Register Your AppIn your project’s settings.py:
Python
INSTALLED_APPS = [
# … default apps …
'gfg', # your app name
]
Step 2. Define Models
Define an intermediate model using the through parameter in the ManyToManyField in gfg/models.py.
Python
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=128)
price = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return self.name
class Customer(models.Model):
name = models.CharField(max_length=128)
age = models.IntegerField()
items_purchased = models.ManyToManyField(Item, through='Purchase')
def __str__(self):
return self.name
class Purchase(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
date_purchased = models.DateField()
quantity_purchased = models.IntegerField()
Step 3. Register Models in Admin
So you can view/edit them in Django’s admin UI:
Python
from django.contrib import admin
from .models import Item, Customer, Purchase
admin.site.register(Item)
admin.site.register(Customer)
admin.site.register(Purchase)
Step 4. Make & Apply Migrations
Generate and apply the database schema using the following commands:
Step 5. Create Sample Data in the Shellpython manage.py makemigrations gfg
python manage.py migrate
Activate the shell using this command:
python manage.py shell
Now lets' create instances of our Purchase model using the codes below in the shell.
1. Import models
from gfg.models import Item, Customer, Purchase
from datetime import date
2. Create one item and one customer
i = Item.objects.create(name="Water Bottle", price=100)
c = Customer.objects.create(name="Abhishek", age=21)
3. Create the intermediate record
p = Purchase.objects.create(
item=i,
customer=c,
date_purchased=date(2019, 7, 7),
quantity_purchased=3
)
4. Verify the relations:
Snapshot of the shellprint(c.items_purchased.all()) # [<Item: Water Bottle>]
print(i.customer_set.all()) # [<Customer: Abhishek>]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4