DictField key validation #9869
Unanswered
snowman2
asked this question in
Ideas & Suggestions
Replies: 1 comment
-
|
That could be a good approach. To support this, we’ll just need to extend the logic of class DictField(Field):
def __init__(self, key_field=None, child=None, **kwargs):
self.key_field = key_field
self.child = child
super().__init__(**kwargs)
if self.key_field:
self.key_field.bind(field_name='', parent=self)and deserialization part; def to_internal_value(self, data):
if not isinstance(data, dict):
self.fail('not_a_dict', input_type=type(data).__name__)
ret = {}
for key, value in data.items():
# 1. key validation
if self.key_field:
try:
validated_key = self.key_field.run_validation(key)
except ValidationError as e:
raise ValidationError({key: e.detail})
else:
validated_key = str(key)
# 2. value validation
if self.child:
ret[validated_key] = self.child.run_validation(value)
else:
ret[validated_key] = value
return retFor example, this idea also provides the DRF with the following flexibility: def validate_prefix(value):
if not value.startswith('attr_'):
raise serializers.ValidationError("Key should start with 'attr_' ")
class DynamicAttributesSerializer(serializers.Serializer):
attributes = serializers.DictField(
key_field=serializers.CharField(validators=[validate_prefix]),
child=serializers.CharField()
)That sounds like a reasonable and good suggestion to me. It would be nice to hear the maintainers’ thoughts as well. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
https://stackoverflow.com/questions/75148782/django-rest-framework-serializers-dictfield-constraint-on-possible-keys
It would also be nice to run validators on the keys as well. Adding
keyas serializer Field would enable that in a more DRF way of doing things.Beta Was this translation helpful? Give feedback.
All reactions