The Wayback Machine - https://web.archive.org/web/20240118171211/https://www.geeksforgeeks.org/intermediate-fields-in-django-python/
Open In App
Related Articles

Intermediate fields in Django | Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Prerequisite: Django models, Relational fields in Django
In Django, a many-to-many relationship exists between two models A and B, when one instance of A is related to multiple instances of B, and vice versa. For example – In a shop management system, an Item and a Customer share a many-to-many relationship, as one customer can buy multiple items, and multiple customers can buy the same item. 

However, there may be some fields that are neither specific to the customer, nor to the item bought, but rather to the purchase of the item by the customer. e.g. quantity purchased date of buying, etc. For storing such intermediary data, we need intermediate models. We need to specify the intermediate model via through parameter in ManyToManyField.

For our example, the code would look something like this.

Python3




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()


Now lets see how we can create instances of our Purchase model. 

Python3




i = Item.objects.create(name = "Water Bottle", price = 100)
c = Customer.objects.create(name = "Abhishek", age = 21)
p = Purchase(item = i, customer = c, 
             date_purchased = date(2019, 7, 7), 
             quantity_purchased = 3)
   
p.save()


Python3




c.items_purchased.all()


<QuerySet [<Item: Water Bottle>]>

Python3




i.customer_set.all()


<QuerySet [<Customer: Abhishek>]>

Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 12 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials