Django表单条件只选择一个字段?

时间:2016-05-19 18:43:55

标签: django django-forms

我的应用程序经常出现这样的情况:我在同一个模型中有几个关系,如:

SO =  models.OneToOneField(SOproduct,null=True, blank=True)
PO =  models.OneToOneField(PO,null=True, blank=True)
Produce =  models.OneToOneField(Produce,null=True, blank=True)

但我想确保用户只选择一个。例如,如果有SO那么PO和Produce将保持为空,反之亦然,当Produce选择PO和SO将保持为空时。同样不强制选择其中一个字段

我可以再创建3个表来保持关系,但我不想这样做。

Django中是否有针对此问题的优雅解决方案?

2 个答案:

答案 0 :(得分:1)

您可以通过覆盖ModelForm方法在clean中为此添加验证来执行此操作。

您应该检查是否选择了多个字段。如果是,那么您应该在表单中提出ValidationError

class MyModelForm(forms.ModelForm):

    def clean(self):
        cleaned_data = super(MyModelForm, self).clean()

        so = cleaned_data.get('SO') # get the value for 'SO'
        po = cleaned_data.get('PO') # get the value for 'PO'
        produce = cleaned_data.get('Produce') # get the value for 'Produce' 

        related_fields = [so, po, produce]
        related_fields_selected = [field for field in related_fields if field]

        # check if more than one related fields was selected 
        if len(related_fields_selected)>1: 
           raise forms.ValidationError('Please select only one value')

        return cleaned_data     

答案 1 :(得分:0)

我想你可以定义一个unique_together元选项,它需要三者之间的唯一关系,如果试图设置多个,则会引发ValidationError

class Meta:
    unique_together = (('SO', 'PO', 'Produce'),)
  

违反约束时在模型验证期间引发的ValidationError具有unique_together错误代码。