Skip to content

Commit 35c5be6

Browse files
Add a method for getting serializer field name (OpenAPI) (#7493)
* Add a method for getting serializer field name * Add docs and test Co-authored-by: Tom Christie <tom@tomchristie.com>
1 parent 0cb6937 commit 35c5be6

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

rest_framework/schemas/openapi.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,7 @@ def map_serializer(self, serializer):
523523
continue
524524

525525
if field.required:
526-
required.append(field.field_name)
526+
required.append(self.get_field_name(field))
527527

528528
schema = self.map_field(field)
529529
if field.read_only:
@@ -538,7 +538,7 @@ def map_serializer(self, serializer):
538538
schema['description'] = str(field.help_text)
539539
self.map_field_validators(field, schema)
540540

541-
properties[field.field_name] = schema
541+
properties[self.get_field_name(field)] = schema
542542

543543
result = {
544544
'type': 'object',
@@ -589,6 +589,13 @@ def map_field_validators(self, field, schema):
589589
schema['maximum'] = int(digits * '9') + 1
590590
schema['minimum'] = -schema['maximum']
591591

592+
def get_field_name(self, field):
593+
"""
594+
Override this method if you want to change schema field name.
595+
For example, convert snake_case field name to camelCase.
596+
"""
597+
return field.field_name
598+
592599
def get_paginator(self):
593600
pagination_class = getattr(self.view, 'pagination_class', None)
594601
if pagination_class:

tests/schemas/test_openapi.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,20 @@ class Serializer(serializers.Serializer):
111111
assert data['properties']['default_false']['default'] is False, "default must be false"
112112
assert 'default' not in data['properties']['without_default'], "default must not be defined"
113113

114+
def test_custom_field_name(self):
115+
class CustomSchema(AutoSchema):
116+
def get_field_name(self, field):
117+
return 'custom_' + field.field_name
118+
119+
class Serializer(serializers.Serializer):
120+
text_field = serializers.CharField()
121+
122+
inspector = CustomSchema()
123+
124+
data = inspector.map_serializer(Serializer())
125+
assert 'custom_text_field' in data['properties']
126+
assert 'text_field' not in data['properties']
127+
114128
def test_nullable_fields(self):
115129
class Model(models.Model):
116130
rw_field = models.CharField(null=True)

0 commit comments

Comments
 (0)