mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-27 08:29:59 +03:00
Add output field to serializer method field
This commit is contained in:
parent
abc26d3716
commit
203aed7af2
|
@ -1868,8 +1868,9 @@ class SerializerMethodField(Field):
|
||||||
def get_extra_info(self, obj):
|
def get_extra_info(self, obj):
|
||||||
return ... # Calculate some data to return.
|
return ... # Calculate some data to return.
|
||||||
"""
|
"""
|
||||||
def __init__(self, method_name=None, **kwargs):
|
def __init__(self, method_name=None, output_field=None, **kwargs):
|
||||||
self.method_name = method_name
|
self.method_name = method_name
|
||||||
|
self.output_field = output_field
|
||||||
kwargs['source'] = '*'
|
kwargs['source'] = '*'
|
||||||
kwargs['read_only'] = True
|
kwargs['read_only'] = True
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
|
|
|
@ -377,6 +377,9 @@ class AutoSchema(ViewInspector):
|
||||||
data['type'] = 'object'
|
data['type'] = 'object'
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
if isinstance(field, serializers.SerializerMethodField) and field.output_field:
|
||||||
|
return self.map_field(field.output_field)
|
||||||
|
|
||||||
# Related fields.
|
# Related fields.
|
||||||
if isinstance(field, serializers.ManyRelatedField):
|
if isinstance(field, serializers.ManyRelatedField):
|
||||||
return {
|
return {
|
||||||
|
|
|
@ -132,6 +132,20 @@ class TestFieldMapping(TestCase):
|
||||||
assert data['properties']['ro_field']['nullable'], "ro_field nullable must be true"
|
assert data['properties']['ro_field']['nullable'], "ro_field nullable must be true"
|
||||||
assert data['properties']['ro_field']['readOnly'], "ro_field read_only must be true"
|
assert data['properties']['ro_field']['readOnly'], "ro_field read_only must be true"
|
||||||
|
|
||||||
|
def test_serializer_method_field(self):
|
||||||
|
class MethodSerializer(serializers.Serializer):
|
||||||
|
|
||||||
|
method_field = serializers.SerializerMethodField(output_field=serializers.BooleanField())
|
||||||
|
|
||||||
|
def get_method_field(self, obj):
|
||||||
|
return True
|
||||||
|
|
||||||
|
inspector = AutoSchema()
|
||||||
|
|
||||||
|
inspector.map_serializer(MethodSerializer())
|
||||||
|
data = inspector.components['Method']
|
||||||
|
assert data['properties']['method_field']['type'] == 'boolean'
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.')
|
@pytest.mark.skipif(uritemplate is None, reason='uritemplate not installed.')
|
||||||
class TestOperationIntrospection(TestCase):
|
class TestOperationIntrospection(TestCase):
|
||||||
|
|
Loading…
Reference in New Issue
Block a user