dazai
dazai

Reputation: 716

How can I make a field case insensitive and unique only?

I'm trying to add object to my models that are unique and case insensitive so if I add 'car' first and then I try to add 'cAr' it should return an error. I don't know how to that, though. How can I make this happen?

This is the model:

class Food(models.Model):
    name = models.CharField(max_length=100, unique=True)

    def __str__(self):
        return self.name

This is the serializer:

class FoodSerializer(serializers.ModelSerializer):

    class Meta:
        model = Food
        fields = '__all__'  

Upvotes: 0

Views: 583

Answers (1)

lord stock
lord stock

Reputation: 1201

You can Make your custom LowerCharField and Use it in your Models Just import this class and car and Car can be checked for uniqueness. Here is my solution.

 class LowerCharField(with_metaclass(models.SubfieldBase, models.CharField)):
        def __init__(self, *args, **kwargs):
            self.is_lowercase = kwargs.pop('lowercase', False)
            super(LowerCharField, self).__init__(*args, **kwargs)
    
        def get_prep_value(self, value):
            value = super(LowerCharField, self).get_prep_value(value)
            if self.is_lowercase:
                return value.lower()
            return value

And You can do this way

class Food(models.Model):
    name =LowerCharField(max_length=128, lowercase=True, null=False, unique=True)

    def __str__(self):
        return self.name

If you want further customization like you may take any input from user i.e car or CAR at the end you may convert to lower and check for uniqueness.

Upvotes: 1

Related Questions