I have a use case targeting developers sending extra data to my API. I want my API to have a strict typing system via Django Rest Framework Serializer validation. However, if a user sends partially invalid data, I want to ignore that data if the field is optional rather than return a 400 response. For example, consider a key-value tags field
tags = serializers.DictField(child=serializers.CharField(), required=False)
Valid data for the tags field might look like {"foo": "bar"}
. Invalid data could look like {"foo": "bar", "invalid": {{"some": "object"}}
as the value for "invalid" is an object and not a string. DRF is_valid will consider this invalid. validated_data will not be populated.
> serializer.is_valid()
False
> serializer.validated_data
{}
Because this field is not required and other tags might be valid, I'd want this returned instead
> serializer.is_valid()
True
> serializer.validated_data
{'another_field': 'a', 'tags': [{'foo': 'bar']}
Is there a way to make optional fields ignore invalid data instead of making the entire serializer invalid while still using a Django Rest Framework serializer and benefiting from the other validation and normalization performed?
question from:
https://stackoverflow.com/questions/65848389/django-rest-framework-serializer-how-to-allow-optional-fields-to-be-ignored-wh 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…