Django: Most Efficient Many-to-Many Complement Without End-to-End Model?

I need to simulate:

class A(Model):
    b = models.ManyToManyField(B)

class B(Model):
    # fields

      

What's the most efficient way to add a large number of existing instances B

to a relationship?

+3


source to share


1 answer


As of django 1.4, you can use a methodbulk_create

to create many B objects in one go, then add them to AbManyToMany

So, create a list of objects B

, create them in bulk, then add them (all at once) to ManyToMany

your A

instance (s) relation :



l = [
    B(...),
    B(...),
    B(...),
    ...
]
B.objects.bulk_create(l)
a.b.add(*o)

      

+3


source







All Articles