Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Uploading images in Django - Python
Next article icon

Prerequisite:Django models,Relational fields in Django

In Django, amany-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 ashop management system:

  • A Customer can purchase multiple Items.
  • An Item can be purchased by multiple Customers.

To model this, Django offers theManyToManyField. 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’ssettings.py:

Python
INSTALLED_APPS=[# … default apps …'gfg',# your app name]

Step 2. Define Models

Define an intermediate model using thethroughparameter in theManyToManyFieldingfg/models.py.

Python
fromdjango.dbimportmodelsclassItem(models.Model):name=models.CharField(max_length=128)price=models.DecimalField(max_digits=5,decimal_places=2)def__str__(self):returnself.nameclassCustomer(models.Model):name=models.CharField(max_length=128)age=models.IntegerField()items_purchased=models.ManyToManyField(Item,through='Purchase')def__str__(self):returnself.nameclassPurchase(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 canview/edit them in Django’s admin UI:

Python
fromdjango.contribimportadminfrom.modelsimportItem,Customer,Purchaseadmin.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>]

djano_02
Snapshot of the shell

Improve
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp