Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate specific field in DRF serializer

I have a model with a JSONField.

model.py

class Categories(models.Model):
     type = models.CharField(max_length=20)
     name = models.CharField(max_length=500)
     details = JSONField(blank=True, null=True)

Currently I'm using serializers.ModelSerializer for serializing this above model:

serializers.py

class CategoriesSerializer(serializers.ModelSerializer):
     class Meta:
         model = Categories
         fields = ('id', 'type', 'name', 'details')

Due to this, the details field is only checked to contain valid json. What i really need to do is to perform some custom validation based on the Json Schema defined for details field. However since I don't want any other custom validations for rest of the fields, I would like to keep using the validations provided by serializers.ModelSerializer. Is there any way I can override a validation for just one field, probably by writing a custom serializer for just the details field?

Note question is not about how to write a custom Validator, but about how to use that custom validator on a field in the serializer inheriting ModelSerializer

like image 469
Ishan Khare Avatar asked May 18 '26 08:05

Ishan Khare


1 Answers

DRF's serializers provide field level validation option. You can perform details field validation by implementing validate_details method:

class CategoriesSerializer(serializers.ModelSerializer):
     class Meta:
         model = Categories
         fields = ('id', 'type', 'name', 'details')

     def validate_details(self, value):
        if value['not_valid']:
            raise serializers.ValidationError("Not valid")
        return value
like image 170
neverwalkaloner Avatar answered May 20 '26 21:05

neverwalkaloner