Django: saving multiple ManyToMany fields in a transaction

this is a view of my models:

class B(models.Model):
   """I'm a dummy model, so doesn't pay atention of what I do"""
   name = models.CharField(max_length=250)

class A(models.Model):
   name = models.CharField(max_length=250)
   many_b = models.ManyToManyField(B)

Now suppose I have a list of objects B. And the only object Ato be associated with this Bs. Something like that:

a = A.objects.get(id=1)
list_of_b = [B<name='B1'>,B<name='B2'>,B<name='B3'>,]

Now I relate to them as follows:

for b_object in list_of_b:
   a.many_b.add(b_object)

Is there a way to add all objects of B to one transaction? Perhaps in one method, for example:

a.many_b.addList(b) #This doesn't exist
+5
source share
2 answers

From the docs :

>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)

So, if you have a list, use the argument extension:

a.many_b.add(*list_of_b)
+5
source

I assume you want this in some kind of voluminous insert?

, Django TRUNK, 1.3!

: http://www.caktusgroup.com/blog/2011/09/20/bulk-inserts-django/

+1

All Articles