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 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.
Now lets see how we can create instances of our Purchase model.
<QuerySet [<Item: Water Bottle>]>
<QuerySet [<Customer: Abhishek>]>