使用具有Multiselect的中间表进行管理的Django M2M关系问题

时间:2019-04-24 17:59:45

标签: django django-models django-admin m2m django-intermediate-table

我正在通过设置中间表来处理m2m关系。问题是我需要显示多选而不是正常的dorpdown,但是当我选择多个项目并保存时会出现错误。

ValueError: Cannot assign "<QuerySet [<Facility: facility1>, <Facility: facility2>]>": "Property.facility" must be a "Facility" instance.

我还在admin.TabularInline中展示了该模型,它使我每行只能选择一个项目,因为表格内联可以插入多种表格。

我尝试了多种解决方案,例如自定义保存和许多其他内容,以及一些如何保存该问题的方法,但随后出现问题。我只需要显示一个带有multiselect小部件的表单即可执行此选择。

models.py


class Facility(models.Model):
    name = models.CharField(max_length=200)

class Property(models.Model):
    name = models.CharField(max_length=200)
    area = models.CharField(max_length=200)
    facility = models.ManyToManyField(Facility, through="PropertyFacility")

class PropertyFacility(models.Model):
    prop = models.ForeignKey(
        Property, related_name="facilities", on_delete=models.CASCADE
    )
    facility = models.ForeignKey(
        Facility, related_name="properties", on_delete=models.CASCADE
    )

admin.py


from django.contrib.admin.widgets import FilteredSelectMultiple
from django.utils.translation import ugettext_lazy as _

class PropertyFacilityForm(forms.ModelForm):
    facility = forms.ModelMultipleChoiceField(Facility.objects.all(), required=True, widget=FilteredSelectMultiple(_('ss'), False, attrs={'rows':'10'})

class PropertyFacilityInline(admin.TabularInline):
    model = Property.facility.through
    form = PropertyFacilityForm

class PropertyAdmin(TabbedModelAdmin):
    model = Property
    tab_facilities = (PropertyFacilityInline,)
    tab_property = (
        (
            "Property Details",
            {
                "fields": (
                    "name",
                    "area",
                )
            },
        ),
    )

    tabs = [
        ("Property", tab_property),
        ("Facilities", tab_facilities),
    ]

它让我这样在管理员上显示 在这里您可以看到我可以选择多个选择,但此处的表单应该是一个而不是多个。

我只想显示一个带有多选小部件的表单,该表单允许我多选并保存它,然后在change_view上显示选中的一个和剩下的未选中的。

1 个答案:

答案 0 :(得分:0)

我通过添加一些自定义逻辑来保存m2m字段来解决此问题。

admin.py

class PropertyForm(forms.ModelForm):
    facility = forms.ModelMultipleChoiceField(Facility.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Property
        fields = ["id", "name", "area", "city"]

    def save(self, commit=True):
        prop_facilities = self.cleaned_data.pop('facility')
        instance = forms.ModelForm.save(self, commit=False)
        instance.facility.clear()
        for facility in prop_facilities:
            PropertyFacility.objects.create(facility=facility, prop=instance)
        return instance


class PropertyAdmin(TabbedModelAdmin):
    model = Property
    tab_facilities = (("Facilities", {"fields": ("facility", )},),)
    tab_property = (
        (
            "Property Details",
            {
                "fields": (
                    "name",
                    "area",
                )
            },
        ),
    )

    tabs = [
        ("Property", tab_property),
        ("Facilities", tab_facilities),
    ]