views:

582

answers:

2

Hi all.

I would like to merge one querysets related objects with another querysets related objects. Some sample code to explain:

## Models
# sample models to illustrate problem
class PetShop(models.Model):
    id = models.AutoField(primary_key=True)
    shop_name = models.CharField(maxlength=255)
    cats = models.ManyToManyField(Cat)

class Cat(models.Model):
    id = models.AutoField(primary_key=True)
    cat_name = models.CharField(maxlength=50, blank=True)


## View
def MergePetsInShop(request):
    source_shop = PetShop.objects.get(pk=2)
    destination_shop = PetShop.objects.get(pk=3)

    #Somehow merge CATS from one shop to the other
    result = merge(source_shop.cats,destination_shop.cats)

    #save()

How can I do this properly?

Many thanks.

+1  A: 

You can take advantage of the fact that Django's many-to-many manager functions add and remove accept any number of positional arguments. In this case, I'd try:

destination_shop.cats.add(*source_shop.cats.all())
Jarret Hardie
A: 

I highly recommend Jarrets method above. In case someone wanted to see the solution I nearly used but did not (this does work by the way if it's what you need):

@login_required
def MergePetsBetweenShops(request):
    src = int(request.__getitem__("source_shop"))
    dest = int(request.__getitem__("destination_shop"))
    srcShop = PetShop.objects.get(pk=src)
    destShop = PetShop.objects.get(pk=dest)  
    srcPets = srcShop.cats.all()
    amtMerged = srcPets.cats.count()
    for p in srcPets:
         destShop.cats.add(p) 
         destShop.save()
    return HttpResponse("Cats that were moved: "+str(amtMerged), mimetype='application/javascript')

Method names, vars used are ficticious, to protect the innocent.

Darryl