Categories
Python Answers

How to create an object for a Django model with a many to many field?

Spread the love

To create an object for a Django model with a many to many field, we can get the through model from the entity we want to create the objects many to many relation for.

For instance, we write

from django.db import models

class Users(models.Model):
    pass

class Sample(models.Model):
    users = models.ManyToManyField(Users)

to add the Sample model.

Then we write

Users().save()
Users().save()

ThroughModel = Sample.users.through

users = Users.objects.filter(pk__in=[1,2])

sample_object = Sample()
sample_object.save()

ThroughModel.objects.bulk_create([
    ThroughModel(users_id=users[0].pk, sample_id=sample_object.pk),
    ThroughModel(users_id=users[1].pk, sample_id=sample_object.pk)
])

to get the users model from Sample with

ThroughModel = Sample.users.through

Then we create a Sample object with

sample_object = Sample()
sample_object.save()

Then we create the users with

ThroughModel.objects.bulk_create([
    ThroughModel(users_id=users[0].pk, sample_id=sample_object.pk),
    ThroughModel(users_id=users[1].pk, sample_id=sample_object.pk)
])

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *