Django ModelChoiceField - use something other than id?

后端 未结 3 1630
礼貌的吻别
礼貌的吻别 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:34

    ModelChoiceFields are meant to be used to select between a choice of existing model instances. This is almost always best represented by some form of Select field.

    That said do you really have a FK from address to postal_code as you're implying. What are you storing on a PostalCode table to justify the extra table that will need to be joined in for every address related query?

    For most cases postal_code should simply be a CharField and in that case if you want to validate that the value is valid you can use the choices attribute with a list of valid postal codes. Keep in mind that maintaining a list of valid postal codes by hand is a huge hassle.

    If you really have a PostalCode table and think it's a good idea (which in some cases it could be) you may want to consider actually using the postal_code as the primary key rather than the default autoincrement since it's necessarily unique, makes your data more exportable, and solves your issue with validation.

提交回复
热议问题