Django模型形式:m2m的反面不保存

时间:2018-06-15 11:39:01

标签: django django-forms django-orm

从Django 1.8(python 2.7)升级到Django 2.0(python 3.6)后,我在这个表单中出错并反转m2m小部件:

models.py
class Treatment(Model):
  ...

class Specialty(Model):
  treatment = models.ManyToManyField(Treatment, related_name='specialties', blank=True)
  ...

。 这是治疗模型的表格。它还允许编辑专业(反向m2m)。它在升级之前运行良好。

forms.py
class TreatDetail(forms.ModelForm):
    specialties = forms.ModelMultipleChoiceField(
        queryset=Specialty.objects.all().order_by('specialty_de'),
        required=False,
        widget=FilteredSelectMultiple('Specialties', False),

    )


    def save(self, commit=True):
        treatment = super(TreatDetail, self).save(commit=False)

        if commit:
            treatment.save()

        if treatment.pk:
            treatment.specialties = self.cleaned_data['specialties']
            self.save_m2m()

        return treatment

    def __init__(self, *args, **kwargs):
        super(TreatDetail, self).__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            self.fields['specialties'].initial = self.instance.specialties.all()

    class Meta:
        model = Treatment
        fields = (
            'top_treatment',
            'treatment_de',
            ....)

我收到此错误:

  

TypeError在/ customadmin / treatdetail / 2 / de /直接赋值给   禁止多对多集的反面。使用   special.set()代替。

     

treatment.specialties = self.cleaned_data ['specialties']

当然我试过了:

treatment.specialties.set = self.cleaned_data['specialties']

错误消失,但不保存反向m2m关系。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

你做错了。您必须在Django 2.0中将项目添加到M2M关系,如this

treatment.specialties.add(self.cleaned_data['specialties'])

如果self.cleaned_data['specialties']特色的列表 - 您必须对它们进行迭代,并以相同的方式逐一添加到treatment.specialties