Intermediate fields in Django | Python

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 which 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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_puchased = 3)
  
p.save()

chevron_right


 

filter_none

edit
close

play_arrow

link
brightness_4
code

c.items_purchased.all()

chevron_right


<QuerySet [<Item: Water Bottle>]>

 

filter_none

edit
close

play_arrow

link
brightness_4
code

i.customer_set.all()

chevron_right


<QuerySet [<Customer: Abhishek>]>


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.