python - 在 Djano 表单中组合 ModelChoiceFields 以保存在单个 ManyToManyField 中
问题描述
当我保存到数据库时ModelForm
,我想将一系列组合ModelChoiceFields
成一个 ManyToMany 字段。
所以我的模型形式是这样的:
class ExampleForm(forms.ModelForm):
fulltime = forms.ModelChoiceField(
queryset = Type.objects.filter(tag_type=jb_models.F_PTIME),
)
optional = forms.ModelChoiceField(
queryset = Type.objects.filter(tag_type=jb_models.OPTIONAL),
)
class Meta:
model = Job
fields = ('jobtype', 'title', \
'fulltime','optional')
widgets = {
'jobtype': forms.HiddenInput(),
'title': forms.TextInput(attrs={'size':50}),
}
def save(self, commit=True):
instance = super().save(commit=False)
instance.jobtype.set(self.cleaned_data['fulltime'])
instance.jobtype.add(self.cleaned_data['optional'])
instance.save()
return instance
这给了我 TypeError 对象不可迭代。我应该如何处理这个?
解决方案
方法的参数set()
应该是对象列表,因此您可以使用以下方式包装对象[]
:
def save(self, commit=True):
instance = super().save()
instance.jobtype.set([self.cleaned_data['fulltime']])
instance.jobtype.add(self.cleaned_data['optional'])
return instance
还要注意你应该instance
在设置它的多对多关系之前保存,否则你会得到错误:
ValueError: 'Job' 实例需要有一个主键值才能使用多对多关系。
检查此文档。
推荐阅读
- javascript - Create React App 提供的 react-scripts 包需要依赖:
- vb.net - 文件中的 AutoCAD 块比较
- javascript - Javascript:在数组中查找连续数字时保持关闭
- java - 如何在 TextView 中动态排列文本
- ruby - 拆分函数后如何将数组转换为字符串
- python - Django - OneToOneField 未在管理员中填充
- jquery - Jquery Mapael:如何使用 HTML 表格数据来替换这个硬编码示例?
- c# - 在直接调用委托的情况下如何减轻“访问修改的闭包”
- python-imaging-library - 打开的文件太多
- xcode - 如何在启动 Mac os 时自动加载 kext?