Skip to content

Instantly share code, notes, and snippets.

@niklio
Last active March 19, 2017 00:11
Show Gist options
  • Save niklio/dba176e188c52c87e0b028c70825de55 to your computer and use it in GitHub Desktop.
Save niklio/dba176e188c52c87e0b028c70825de55 to your computer and use it in GitHub Desktop.
DRF Dynamic Serializer
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
Django rest framework dynamic serializer based on
http://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields.
Gets the lists 'fields' and 'exclude' directly from the query parameters so it expects
the url to look something like:
https://api.example.com/resource/?fields=id&fields=name&exclude=id
"""
def __init__(self, *args, **kwargs):
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
existing = set(self.fields.keys())
fields = set(self._context['request'].query_params.getlist('fields', existing))
exclude = set(self._context['request'].query_params.getlist('exclude', []))
# Drop any fields in not in fields or in exclude
for field_name in existing - (fields - exclude):
self.fields.pop(field_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment