2

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

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

我怎样才能正确地做到这一点?

非常感谢。

4

2 回答 2

1

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

destination_shop.cats.add(*source_shop.cats.all())
于 2009-04-06T12:24:17.797 回答
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')

使用的方法名、vars 都是虚构的,以保护无辜。

于 2009-04-13T20:35:57.733 回答