Django: How to merge two related querysets in Django 0.96?

你离开我真会死。 提交于 2019-12-11 01:43:47

问题


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:


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())



回答2:


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.



来源:https://stackoverflow.com/questions/720966/django-how-to-merge-two-related-querysets-in-django-0-96

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!