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
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>]>
- Python | Relational fields in Django models
- URL fields in serializers - Django REST Framework
- Serializer Fields - Django REST Framework
- Render Django Form Fields Manually
- String Fields in Serializers - Django REST Framework
- Numeric fields in serializers - Django REST Framework
- Django model data types and fields list
- Boolean Fields in Serializers - Django REST Framework
- Date and time fields in serializers - Django REST Framework
- Core arguments in serializer fields - Django REST Framework
- Choice Selection Fields in serializers - Django REST Framework
- File upload Fields in Serializers - Django REST Framework
- Intermediate Coding Problems in Python
- 7 Cool Python Project Ideas for Intermediate Developers
- Data Classes in Python | Set 3 (dataclass fields)
- Views In Django | Python
- Weather app using Django | Python
- Django Migrations | Python
- Python | Django News App
- Django URL patterns | Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.