Django:如何在Django 0.96中合并两个相关的查询集?

时间:2009-04-06 10:58:30

标签: django django-models django-queryset

我想将一个查询集相关对象与另一个查询集相关对象合并。 一些示例代码解释:

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

我该如何正确地做到这一点?

非常感谢。

2 个答案:

答案 0 :(得分:1)

您可以利用Django的多对多管理器函数addremove接受任意数量的位置参数这一事实。在这种情况下,我会尝试:

destination_shop.cats.add(*source_shop.cats.all())

答案 1 :(得分:0)

我强烈推荐上面的Jarrets方法。如果有人想看到我几乎使用但没有的解决方案(如果它是您需要的话,这确实有用):

@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')

方法名称,使用的变量是虚构的,以保护无辜者。