mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-02-03 05:04:31 +03:00
Merge pull request #1818 from tituomin/serializer-subclass-mapping
Better mapping for custom model fields to serializer fields.
This commit is contained in:
commit
e8fac28d88
|
@ -625,6 +625,20 @@ class ModelSerializerOptions(SerializerOptions):
|
||||||
self.write_only_fields = getattr(meta, 'write_only_fields', ())
|
self.write_only_fields = getattr(meta, 'write_only_fields', ())
|
||||||
|
|
||||||
|
|
||||||
|
def _get_class_mapping(mapping, obj):
|
||||||
|
"""
|
||||||
|
Takes a dictionary with classes as keys, and an object.
|
||||||
|
Traverses the object's inheritance hierarchy in method
|
||||||
|
resolution order, and returns the first matching value
|
||||||
|
from the dictionary or None.
|
||||||
|
|
||||||
|
"""
|
||||||
|
return next(
|
||||||
|
(mapping[cls] for cls in inspect.getmro(obj.__class__) if cls in mapping),
|
||||||
|
None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class ModelSerializer(Serializer):
|
class ModelSerializer(Serializer):
|
||||||
"""
|
"""
|
||||||
A serializer that deals with model instances and querysets.
|
A serializer that deals with model instances and querysets.
|
||||||
|
@ -899,14 +913,16 @@ class ModelSerializer(Serializer):
|
||||||
models.URLField: ['max_length'],
|
models.URLField: ['max_length'],
|
||||||
}
|
}
|
||||||
|
|
||||||
if model_field.__class__ in attribute_dict:
|
attributes = _get_class_mapping(attribute_dict, model_field)
|
||||||
attributes = attribute_dict[model_field.__class__]
|
if attributes:
|
||||||
for attribute in attributes:
|
for attribute in attributes:
|
||||||
kwargs.update({attribute: getattr(model_field, attribute)})
|
kwargs.update({attribute: getattr(model_field, attribute)})
|
||||||
|
|
||||||
try:
|
serializer_field_class = _get_class_mapping(
|
||||||
return self.field_mapping[model_field.__class__](**kwargs)
|
self.field_mapping, model_field)
|
||||||
except KeyError:
|
|
||||||
|
if serializer_field_class:
|
||||||
|
return serializer_field_class(**kwargs)
|
||||||
return ModelField(model_field=model_field, **kwargs)
|
return ModelField(model_field=model_field, **kwargs)
|
||||||
|
|
||||||
def get_validation_exclusions(self, instance=None):
|
def get_validation_exclusions(self, instance=None):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user