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.
You can take advantage of the fact that Django’s many-to-many manager functions
addandremoveaccept any number of positional arguments. In this case, I’d try: