Unique fields that allow nulls in Django

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

    You can add UniqueConstraint with condition of nullable_field=null and not to include this field in fields list. If you need also constraint with nullable_field wich value is not null, you can add additional one.

    Note: UniqueConstraint was added since django 2.2

    class Foo(models.Model):
        name = models.CharField(max_length=40)
        bar = models.CharField(max_length=40, unique=True, blank=True, null=True, default=None)
        
        class Meta:
            constraints = [
                # For bar == null only
                models.UniqueConstraint(fields=['name'], name='unique__name__when__bar__null',
                                        condition=Q(bar__isnull=True)),
                # For bar != null only
                models.UniqueConstraint(fields=['name', 'bar'], name='unique__name__when__bar__not_null')
            ]
    

提交回复
热议问题