首页 > 解决方案 > 使用字典创建模型时动态将数据/模型实例添加到 M2M 字段

问题描述

m2m我正在尝试使用字典创建带有字段的模型。就像是:

data = {fieldA: "hello", fieldB: "world", m2m: [ModelInstance, ]}    
model_instance.objects.create(**data)

我尝试添加我试图在数组中设置的 m2m 值,但我不断收到异常

TypeError: Direct assignment to the forward side of a many-to-many set is prohibited.

标签: pythondjangodjango-models

解决方案


创建实例后,您必须添加 m2m-data,如下所示:

data = {fieldA: "hello", fieldB: "world", m2m: [ModelInstance, ]}
m2m_data = data.pop("m2m")  # remove the key from the dict

instance = model_instance.objects.create(**data)
instance.m2m.add(m2m_data)

推荐阅读