简体   繁体   中英

UniqueValidator in drf

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

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()
                        )
                    ]
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM