Skip to content

Add a method for getting serializer field name (OpenAPI) #7493

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions rest_framework/schemas/openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ def map_serializer(self, serializer):
continue

if field.required:
required.append(field.field_name)
required.append(self.get_field_name(field))

schema = self.map_field(field)
if field.read_only:
Expand All @@ -538,7 +538,7 @@ def map_serializer(self, serializer):
schema['description'] = str(field.help_text)
self.map_field_validators(field, schema)

properties[field.field_name] = schema
properties[self.get_field_name(field)] = schema

result = {
'type': 'object',
Expand Down Expand Up @@ -589,6 +589,13 @@ def map_field_validators(self, field, schema):
schema['maximum'] = int(digits * '9') + 1
schema['minimum'] = -schema['maximum']

def get_field_name(self, field):
"""
Override this method if you want to change schema field name.
For example, convert snake_case field name to camelCase.
"""
return field.field_name

def get_paginator(self):
pagination_class = getattr(self.view, 'pagination_class', None)
if pagination_class:
Expand Down
14 changes: 14 additions & 0 deletions tests/schemas/test_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,20 @@ class Serializer(serializers.Serializer):
assert data['properties']['default_false']['default'] is False, "default must be false"
assert 'default' not in data['properties']['without_default'], "default must not be defined"

def test_custom_field_name(self):
class CustomSchema(AutoSchema):
def get_field_name(self, field):
return 'custom_' + field.field_name

class Serializer(serializers.Serializer):
text_field = serializers.CharField()

inspector = CustomSchema()

data = inspector.map_serializer(Serializer())
assert 'custom_text_field' in data['properties']
assert 'text_field' not in data['properties']

def test_nullable_fields(self):
class Model(models.Model):
rw_field = models.CharField(null=True)
Expand Down