Home > Software design >  Unique field case insensitive constraint
Unique field case insensitive constraint

Time:03-07

I am trying to ensure that all tags are unique when converted to lowercase. However, when I run the migrate on the following model I receive the following error:


api.Tag: (models.E012) 'constraints' refers to the nonexistent field 'Lower(F(name))'.

class Tag(models.Model):
  name = models.CharField(max_length=30)


  class Meta:
    constraints = [
        models.UniqueConstraint(
            fields=[Lower('name')],
            name='unique_name'
        ),
    ]

CodePudding user response:

Since , you can work with expressions in a UniqueConstraint [Django-doc], so:

class Tag(models.Model):
    name = models.CharField(max_length=30)
    
    class Meta:
        constraints = [
            models.UniqueConstraint(
                Lower('name'),
                name='unique_name'
            )
        ]
  • Related