作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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
另请注意,在设置多对多关系之前,您应该保存实例
,否则您会收到错误:
ValueError: 'Job' instance needs to have a primary key value before a many-to-many relationship can be used.
检查这个docs .
关于python - 在 Django 表单中组合 ModelChoiceField 以保存在单个 ManyToManyField 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51002076/
我是一名优秀的程序员,十分优秀!