python - 使用字典创建模型时动态将数据/模型实例添加到 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.
解决方案
创建实例后,您必须添加 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)
推荐阅读
- android - 在路径上找不到类“android.support.design.internal.NavigationMenuItemView”:DexPathList
- openssl - 当我在生成 PFX 文件时不包含 .cert 文件的所有层次结构时会发生什么
- android - 当设备被锁定和休眠时,Android 上的 React Native App 停止执行
- java - 使用 JPQL 加入标准
- ruby-on-rails - 如何使用基本身份验证访问另一个应用程序
- datagrip - 自动大写 datagrip 中的内容
- inno-setup - 如何使用 ISPP 将文件大小拆分为 DwinsHs_Check 函数的 lo / hi 位
- r - 如何在 R 中构建以下模型
- java - 使用 apache PDFBox 运行以下代码时出现 java.net.ConnectException
- jhipster - jhipster 登录弹出窗口出现在页面中,而不是作为弹出窗口