On Sat, Jun 6, 2009 at 5:11 PM, Julian<maili...@julianmoritz.de> wrote:
>
> hello,
>
> i have a queryset and a model with a manytomany-relationship, let's
> say a pizza has toppings.
>
> my pizza margharita has already some toppings and now i retrieve a
> queryset of some more and want to add them to the pizza:
>
> for topping in toppings:
>    pizza.toppings.add(topping)
>
> the problem is: everytime i call add, the pizza is stored again in the
> database and an insert statement is done. how can I avoid this? for my
> case it would be much better if I could do something like:
>
> pizza.toppings.add(toppings)
>
> to add all toppings in one step.

You're very close:

pizza.toppings.add(*toppings)

will do exactly what you want, and will be executed as a single
insert. The '*' operator effectively unrolls the toppings list into a
series of arguments - essentially, this call is the equivalent of
saying:

pizza.toppings.add(toppings[0], toppings[1], toppings[2],...

but without actually needing to know the number of toppings in advance.

Alternatively, you can completely overwrite the existing set of
toppings with a new set:

pizza.toppings = toppings

This will be issued as a delete and an insert - a delete to remove
existing items, and an insert to add the new items.

Yours,
Russ Magee %-)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to