Django:如何在Django 0.96中合并两个相关的查询器? [英] Django: How to merge two related querysets in Django 0.96?
本文介绍了Django:如何在Django 0.96中合并两个相关的查询器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将一个查询相关对象与另一个查询相关对象进行合并。
一些示例代码解释:
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()
如何正确执行?
非常感谢。
推荐答案
您可以利用Django的多对多管理员功能添加
an d 删除
接受任意数量的位置参数。在这种情况下,我将尝试:
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())
这篇关于Django:如何在Django 0.96中合并两个相关的查询器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文