简体   繁体   English

Django:在事务中保存多个ManyToMany字段

[英]Django: Saving multiple ManyToMany fields within a transaction

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)

Now, suppose I have a list of B objects. 现在,假设我有一个B对象列表。 And a single A object that will be related to that B s. 还有一个与该B相关的A对象。 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)

Is there any way to add all the B objects in a single transaction? 有没有办法在单个事务中添加所有B对象? Maybe in a single method, like: 也许在一个方法中,例如:

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

From the docs : 来自文档

>>> john = Author.objects.create(name="John")
>>> paul = Author.objects.create(name="Paul")
>>> george = Author.objects.create(name="George")
>>> ringo = Author.objects.create(name="Ringo")
>>> entry.authors.add(john, paul, george, ringo)

So if you have a list, use argument expansion: 因此,如果您有一个列表,请使用参数扩展:

a.many_b.add(*list_of_b)

I guess what you want is a kind of bulk insert right? 我想你想要的是一种批量插入吗?

As far as I know this is just available in the Django TRUNK not in 1.3! 据我所知,这只是在Django TRUNK中不在1.3中!

check it out some tutorial: http://www.caktusgroup.com/blog/2011/09/20/bulk-inserts-django/ 查看一些教程: http//www.caktusgroup.com/blog/2011/09/20/bulk-inserts-django/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM