UniqueValidator in drf

Viewed 4651

my model has a field:

name = models.CharField(max_length=255, blank=True, null=True)

in serializer, I am trying to raise a unique validation error

name = serializers.CharField(validators=[UniqueValidator(queryset=Department.objects.all(),
                                        message=("Name already exists"))])

but it does not work, because the data comes to the serializer in this format name: {en: "drink"}, in db fields are populated with drink only.

I can raise an error in the create method, but I want to raise the error on the serializer. appreciate any advice. I'm in a hurry. sorry for any inconvenience.

Thanks in advance

3 Answers

I would highly suggest that you use Django Rest Framework's Serializer Field-Level Validation, which allows you to do custom validation for your field.

like the following:

    name = serializers.CharField()
    ...
    def validate_name(self, value):
        # I assumed that you will that the string value, is a JSON object.
        entered_name = json.loads(value).get('en', None)
        if entered_name and Department.objects.filter(name__exact=entered_name).exists():
            raise serializers.ValidationError("Name already exists!")
        # You need to return the value in after validation.
        return value
     ...

You can do this below your meta class in Serializers.py as it will raise error saying error name must be unique

class Meta:
    model = YourModel

    fields= ('name',) 
    extra_kwargs = {
                'name': {
                    'validators': [
                        UniqueValidator(
                            queryset=YourModelName.objects.all()
                        )
                    ]
                }
            }

i failed to use UniqueValidator so i hacked UniqueTogetherValidator.

Like this;

import it:

from rest_framework.validators import UniqueTogetherValidator

then:

class NameSerializer(serializers.ModelSerializer):
    class Meta:
        model = NameOfModel
        fields = ['id', 'name']
        validators = [
            UniqueTogetherValidator(
                queryset=NameOfModel.objects.all(),
                fields=['name']
            )
        ]

Incase you want the name field to be unique.

Reference: [Here]:https://www.django-rest-framework.org/api-guide/validators/#uniquetogethervalidator

Related