这是我的模型的代表:
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对象列表.还有一个与该Bs相关的A对象.像这样的东西:
a = A.objects.get(id=1)
list_of_b = [B<name='B1'>,B<name='B2'>,B<name='B3'>,]
我现在与他们联系的方式是这样的:
for b_object in list_of_b:
a.many_b.add(b_object)
有没有办法在单个事务中添加所有B对象?也许在一个方法中,例如:
a.many_b.addList(b) #This doesn't exist
解决方法:
>>> 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)
因此,如果您有一个列表,请使用参数扩展:
a.many_b.add(*list_of_b)