Reputation: 152
it seems to me that the answer is quite simple, but I could not manage to find an it, how do I change the name attribute when serialising using DRF? Check the circle in the image, I just got it from the DRF website in the Metadata section.
Upvotes: 2
Views: 314
Reputation: 477607
As specified on the documentation on metadata [drf-doc]. You probably use the SimpleMetadata
class [GitHub]. Here we see that the options are determined with:
def determine_metadata(self, request, view): metadata = OrderedDict() metadata['name'] = view.get_view_name() metadata['description'] = view.get_view_description() metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes] metadata['parses'] = [parser.media_type for parser in view.parser_classes] if hasattr(view, 'get_serializer'): actions = self.determine_actions(request, view) if actions: metadata['actions'] = actions return metadata
The get_view_name
of a APIView
[GitHub] is implemented as:
def get_view_name(self): """ Return the view name, as used in OPTIONS responses and in the browsable API. """ func = self.settings.VIEW_NAME_FUNCTION return func(self)
The settings
will thus by default determine the name of the function that calculates the view. This is specified by the VIEW_NAME_FUNCTION
setting [drf-doc] that defaults to 'rest_framework.views.get_view_name'
.
If we inspect the source code of this get_view_name
function [GitHub], we see:
def get_view_name(view): """ Given a view instance, return a textual name to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_NAME_FUNCTION` setting. """ # Name may be set by some Views, such as a ViewSet. name = getattr(view, 'name', None) if name is not None: return name name = view.__class__.__name__ name = formatting.remove_trailing_string(name, 'View') name = formatting.remove_trailing_string(name, 'ViewSet') name = formatting.camelcase_to_spaces(name) # Suffix may be set by some Views, such as a ViewSet. suffix = getattr(view, 'suffix', None) if suffix: name += ' ' + suffix return name
If your view thus contains a .name
attribute, it will use that as the name. You thus can implement your APIView
as:
class SomeAPIView(APIView):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.name = 'Another name than To Do List'
If there is no name
attribute, it will thus take the name of the view, try to get rid fo the View
or ViewSet
suffix, convert the camelcase to spaces, and optionally add a suffix (like 'List'
for an ListAPIView
).
Upvotes: 1