0

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__'  
dazai
  • 766
  • 4
  • 25
  • Read that article - https://concisecoder.io/2018/10/27/case-insensitive-fields-in-django-models/ – marmeladze Apr 16 '21 at 22:52
  • Does this answer your question? [Case insensitive unique model fields in Django?](https://stackoverflow.com/questions/7773341/case-insensitive-unique-model-fields-in-django) – marmeladze Apr 16 '21 at 22:53
  • @marmeladze None of those things seem to change anything in this case – dazai Apr 16 '21 at 23:19
  • 1
    Which DB are you using? If PostgreSQL you could use CIText https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#citext-fields – Iain Shelvington Apr 17 '21 at 04:26

1 Answers1

1

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.

lord stock
  • 1,191
  • 5
  • 32