Django:在一个事务中保存多个ManyToMany字段 [英] Django: Saving multiple ManyToMany fields within a transaction

查看:91
本文介绍了Django:在一个事务中保存多个ManyToMany字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的模型的表示形式

this is the representation of my models:

class B(models.Model):
   """I'm a dummy model, so doesn't pay atention of what I do"""
   name = models.CharField(max_length=250)

class A(models.Model):
   name = models.CharField(max_length=250)
   many_b = models.ManyToManyField(B)

现在,假设我有一个B对象的列表.还有一个与该B相关的A对象.像这样:

Now, suppose I have a list of B objects. And a single A object that will be related to that Bs. Something like this:

a = A.objects.get(id=1)
list_of_b = [B<name='B1'>,B<name='B2'>,B<name='B3'>,]

我现在与他们的联系方式是:

The way I relate them now is this:

for b_object in list_of_b:
   a.many_b.add(b_object)

是否有任何方法可以在单个事务中添加所有B对象?也许用一种方法,例如:

Is there any way to add all the B objects in a single transaction? Maybe in a single method, like:

a.many_b.addList(b) #This doesn't exist

推荐答案

因此,如果您有列表,请使用参数扩展:

So if you have a list, use argument expansion:

a.many_b.add(*list_of_b)

这篇关于Django:在一个事务中保存多个ManyToMany字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆