【问题标题】:Django Form with a one-to-many relationship具有一对多关系的 Django 表单
【发布时间】:2023-07-26 05:01:01
【问题描述】:

我在 Django 中有一个名为 PersonForm 的表单,此表单模型与 Car 具有 一对多关系。当像在 Django Admin 中一样显示 PersonForm 时,我想允许我的用户从汽车等列表中选择/取消选择。这可能吗?我正在寻找有关从哪里开始的信息。

这是我目前所拥有的 PersonForm:

class PersonForm(forms.ModelForm):

    class Meta:
        model = Person
        fields = ('description',)

模型:

class Person(models.Model):
    description = models.CharField(max_length="150")



class Car(models.Model):
    make = models.CharField(max_length="25")
    owner = models.ForeignKey('Person', related_name="Car")

因此,在人员表单中,我需要显示该人是允许选择/取消选择它们的所有者的汽车列表。我假设我可以以形式执行此操作,即使用相关名称之类的名称。

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    我知道这是一个旧线程,但由于我发现自己在搜索时几乎完全被谷歌指向这里,我想我会为其他寻找答案的人提供以下内容。

    我认为答案是使用

    https://docs.djangoproject.com/en/3.1/ref/forms/fields/#modelchoicefield

    https://docs.djangoproject.com/en/3.1/ref/forms/fields/#modelmultiplechoicefield

    有一篇关于如何使用modelmultiplechoicefield的好文章:

    https://medium.com/swlh/django-forms-for-many-to-many-fields-d977dec4b024

    但它也适用于一对多领域。这些允许我们根据模型中的相关字段生成具有多个选择的表单,例如复选框或类似的小部件。

    【讨论】:

      【解决方案2】:

      我没有任何机会使用内联表单集,所以我建议覆盖你的模型的保存方法,我觉得它更干:

      class PersonForm(forms.ModelForm):
          # add a field to select a car
          car = forms.ModelChoiceField(car.objects.all())
      
          class Meta:
              model = Person
              fields = ('description', 'car')
      
           def save(self, commit=True):
              instance = super().save(commit)
              # set Car reverse foreign key from the Person model
              instance.car_set.add(self.cleaned_data['car']))
              return instance
      

      【讨论】:

        【解决方案3】:

        听起来你想要an inline model form。这使您能够从 Person 表单中的 Person 添加/删除 Car 对象。

        之前的链接是针对 inlinemodeladmin 的。下一个链接用于内联表单: https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#modelforms-factory

        【讨论】: