Django ModelChoiceField - use something other than id?

后端 未结 3 1621
礼貌的吻别
礼貌的吻别 2021-02-14 04:07

Say I have an address table and it has a postal_code field -- ModelChoiceField does not allow me to use something other than PKs to validate existence

3条回答
  •  余生分开走
    2021-02-14 04:52

    If postal_code is a foreign key to a PostalCode model that contains valid postal codes I would just use use a CharField and then do a clean like you suggested. My clean method would look like this:

    def clean_postal_code(self):
        try:
            code = PostalCode.objects.get(code_field=self.data['postal_code'])
        except:
            raise forms.ValidationError("Please enter a valid postal code")
        return code
    

提交回复
热议问题