[Django]-Validate specific field in DRF serializer

10👍

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

1👍

The other way around is to validate JSONFiled on Django models level, you can use jsonschema package.

For example

SCHEMA = { put JSON Schema draft here }

Let’s validate

from jsonschema import validate, ValidationError

def validate_json_filed(value):
    try:
        validate(value, SCHEMA)
    except ValidationError as e:
        raise serializers.ValidationError(e)

Then just

name = JSONField(validators=[validate_json_field], default=dict, blank=True)

You can validate rest of the field using DRF validators.

👤copser

Leave a comment