如何添加与固定装置具有 'through' 关系的 ManyToMany 字段?

How to add ManyToMany field with 'through' relation to fixtures?

在测试(固定装置)中,我想添加具有 'through' 关系的 ManyToMany 字段,即

my_field = models.ManyToManyField(SomeModel, through=AnotherModel).

尝试添加像常规 ManyToManyField 一样:

object.my_field.add(my_field)

但它给了我这个警告信息:enter image description here

另外,试过这个:

object.my_field.add(my_field, through_defaults=AnotherModel)

也没用

您只需构建一个 AnotherModel 对象,因此:

AnotherModel.objects<b>.create(firstmodel=object, somemodel=myfield)</b>

如果 AnotherModel 包含没有默认值的额外字段,您也需要指定这些字段。

或者您可以使用 .add(..) [Django-doc],其中 through_defaults 应包含一个 字典 ,其中包含要传递给 AnotherModel 的值:

object.my_field.add(my_field<b>, through_defaults={'field1': 14, 'field2': 25}</b>)

有关 through_defaults 的更多信息,请参阅 Extra fields on many-to-many relationships section of the documentation。这包含一个示例,例如:

beatles.members.set([john, paul, ringo, george], <b>through_defaults={'date_joined': date(1960, 8, 1)}</b>)

在这个例子中beatles对象的members是一个中间模型的ManyToManyField,这里我们填写date(1960, 8, 1)作为[=20的值=] 在该模型中。