Skip to content

Instantly share code, notes, and snippets.

@kkirsanov
Last active March 22, 2019 09:36
Show Gist options
  • Save kkirsanov/bf1a4f7c45a95ec8256abaf187615d98 to your computer and use it in GitHub Desktop.
Save kkirsanov/bf1a4f7c45a95ec8256abaf187615d98 to your computer and use it in GitHub Desktop.
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
based on https://bit.ly/2TnW0ZJ
Usage: api_endpoint/?fields=uid,name,alias,parent
api_endpoint/?fields!=parent
"""
def __init__(self, *args, **kwargs):
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
fields = self.context['request'].query_params.get('fields')
not_fields = self.context['request'].query_params.get('fields!')
if fields:
fields = fields.split(',')
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
elif not_fields:
not_fields = not_fields.split(',')
# Drop any fields that are not specified in the `fields` argument.
for field_name in not_fields:
self.fields.pop(field_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment