Intermediate fields in Django - Python
Last Updated :
14 May, 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:
- A Customer can purchase multiple Items.
- An Item can be purchased by multiple Customers.
To model this, Django offers the ManyToManyField. However, there are cases where you want to store additional information about the relationship itself, such as:
- Quantity of the item purchased
- Date of purchase
- Payment status, etc.
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 App
In 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:
python manage.py makemigrations gfg
python manage.py migrate
Step 5. Create Sample Data in the Shell
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:
print(c.items_purchased.all()) # [<Item: Water Bottle>]
print(i.customer_set.all()) # [<Customer: Abhishek>]
Snapshot of the shell
Similar Reads
Django Models A Django model is a Python class that represents a database table. Models make it easy to define and work with database tables using simple Python code. Instead of writing complex SQL queries, we use Djangoâs built-in ORM (Object Relational Mapper), which allows us to interact with the database in a
8 min read
Django ORM - Inserting, Updating & Deleting Data Django's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Django Basic App Model - Makemigrations and Migrate Django's Object-Relational Mapping (ORM) simplifies database interactions by mapping Python objects to database tables. One of the key features of Django's ORM is migrations, which allow you to manage changes to the database schema.What are Migrations in Django?Migrations are files that store instru
4 min read
Add the slug field inside Django Model The slug field within Django models is a pivotal step for improving the structure and readability of URLs in web applications. This addition allows developers to automatically generate URL-friendly slugs based on titles, enhancing user experience and search engine optimization (SEO). By implementing
4 min read
Intermediate fields in Django - Python Prerequisite: Django models, Relational fields in DjangoIn 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:A Customer can purchase multiple Items.An Item can be
2 min read
Uploading images in Django - Python Prerequisite - Introduction to DjangoUploading and managing image files is a common feature in many web applications, such as user profile pictures, product images, or photo galleries. In Django, you can handle image uploads easily using the ImageField in models.In this article, weâll walk through a
3 min read
Customize Object Names with __str__ Method When you create instances of a Django model, by default, they appear in the Django admin interface and elsewhere as "ModelName object (1)" (or a similar format). This can make it hard to identify records, especially when you have many objects.Why Customize Object Display Names?By default, Django doe
2 min read
Custom Field Validations in Django Models Field validation ensures that the data entered into a model field meets specific rules before itâs saved to the database. While Django provides built-in validations for common checks, custom field validation lets you enforce your own rules, such as verifying formats, length limits, or complex condit
3 min read
Meta Class in Models - Django Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. D
3 min read
How to use Django Field Choices ? Djangoâs choices option lets you limit a model field to a fixed set of values. It helps keep your data clean and consistent, and automatically shows a dropdown menu in forms and the admin instead of a text box.Choices are defined as pairs: the first value is saved to the database, and the second is
2 min read