Django rest framework add custom validator to many=True serializer class -
below serializer class has 1 many=true field itemserializer
class dataserializer(serializers.serializer): items = itemserializer(many=true) now want apply validation on field items, tried
items = itemserializer(many=true, validators=[my_custom_validator]) below validator(function based)
def my_custom_validator(value): # check , validation , raise appropriate validation error but problem validator applied each item 1 one instead of whole list @ once.
so example want check length of items list , if exceed predefined length, should able raise error before executing validation on each item.
i've tried override to_internal_value got valueerror: many values unpack (expected 2)
def to_internal_value(self, data): if len(data.get('items')) > 42: raise serializers.validationerror('length shouldnt more 42') return super(dataserializer, self).to_internal_value(data) note itemserializer can nested serializer itself, mean using serializer field , on. custom field_level method validation won't work here.
to run custom validation before content validation, should override to_internal_value method:
def to_internal_value(self, data): my_custom_validator(data.get('items')) return super(dataserializer, self).to_internal_value(data) otherwise, simple specify custom field-level validation adding
.validate_<field_name> methods serializer subclass. for example:
def validate_items(self, items): if len(items) != 42: raise validationerror('length should 42') return items
Comments
Post a Comment