Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Saving multiple ManyToMany fields within a transaction

this is the representation 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 B objects. And a single A object that will be related to that Bs. Something like this:

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

The way I relate them now is this:

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

Is there any way to add all the B objects in a single transaction? Maybe in a single method, like:

a.many_b.addList(b) #This doesn't exist
like image 748
santiagobasulto Avatar asked Dec 01 '11 15:12

santiagobasulto


People also ask

How do I set many-to-many fields in Django?

Django will automatically generate a table to manage many-to-many relationships. You might need a custom “through” model. The most common use for this option is when you want to associate extra data with a many-to-many relationship.

How do you use many-to-many fields?

You have to save a Topping in the database before you can add it to a Pizza , and vice versa. This is because a ManyToManyField creates an invisible "through" model that relates the source model (in this case Pizza , which contains the ManyToManyField ) to the target model ( Topping ).

How do you implement many-to-many relationships in Django?

To define a many-to-many relationship, use ManyToManyField . What follows are examples of operations that can be performed using the Python API facilities. You can't associate it with a Publication until it's been saved: >>> a1.


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 argument expansion:

a.many_b.add(*list_of_b)
like image 157
Daniel Naab Avatar answered Oct 04 '22 21:10

Daniel Naab


I guess what you want is a kind of bulk insert right?

As far as I know this is just available in the Django TRUNK not in 1.3!

check it out some tutorial: http://www.caktusgroup.com/blog/2011/09/20/bulk-inserts-django/

like image 38
Arthur Neves Avatar answered Oct 04 '22 22:10

Arthur Neves