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.
- [Django]-Serializer return incorrect output
- [Django]-Is it possible to run Apache and IIS on the same machine with one IP-Address (and different ports ?)
- [Django]-How to associate existsing users from django.contrib.auth with Python Social Auth (Google backend)?
- [Django]-Return self.user as foreignkey
- [Django]-Django query for many to many relationship
Source:stackexchange.com