Unique fields that allow nulls in Django

前端 未结 10 1053
闹比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:32

    If you have a model MyModel and want my_field to be Null or unique, you can override model's save method:

    class MyModel(models.Model):
        my_field = models.TextField(unique=True, default=None, null=True, blank=True) 
    
        def save(self, **kwargs):
            self.my_field = self.my_field or None
            super().save(**kwargs)
    

    This way, the field cannot be blank will only be non-blank or null. nulls do not contradict uniqueness

提交回复
热议问题