python - 在 Django 表单中组合 ModelChoiceField 以保存在单个 ManyToManyField 中

标签 python django django-forms

我有一个 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/

相关文章:

Python - sklearn 管道 SVC f_regression - 获取列名称

python - 如何创建一个字典来反向查找每个都有集合的列表项?

python - 如何在动态Django模型中调用属性方法?

django - 获取组中的所有用户 - Django

python - 模块未找到错误 : No module named 'rest_framework' I already installed djangorestframework

python - django 如何通过用户状态更改 __str__ 标签?

django - 如何引用 django 模型表单对象的底层模型?

python - 尝试在 python 中创建一个 virtualenv 并激活它

python - 使用 python 和 BaseProcess 类进行多处理

python - 带有两个提交按钮的 Django 表单。 . .一个需要字段,一个不需要