首页 > 解决方案 > 在 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 对象不可迭代。我应该如何处理这个?

标签: pythondjangodjango-forms

解决方案


方法的参数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' 实例需要有一个主键值才能使用多对多关系。

检查此文档


推荐阅读