Intermediate fields in Django - Python
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:
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.
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:
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>]
