Unique fields that allow nulls in Django

前端 未结 10 1050
闹比i
闹比i 2020-11-28 01:56

I have model Foo which has field bar. The bar field should be unique, but allow nulls in it, meaning I want to allow more than one record if bar field is null,

10条回答
  •  再見小時候
    2020-11-28 02:42

    Because I am new to stackoverflow I am not yet allowed to reply to answers, but I would like to point out that from a philosophical point of view, I can't agree with the most popular answer tot this question. (by Karen Tracey)

    The OP requires his bar field to be unique if it has a value, and null otherwise. Then it must be that the model itself makes sure this is the case. It cannot be left to external code to check this, because that would mean it can be bypassed. (Or you can forget to check it if you write a new view in the future)

    Therefore, to keep your code truly OOP, you must use an internal method of your Foo model. Modifying the save() method or the field are good options, but using a form to do this most certainly isn't.

    Personally I prefer using the CharNullField suggested, for portability to models I might define in the future.

提交回复
热议问题