Last active
March 19, 2017 00:11
-
-
Save niklio/dba176e188c52c87e0b028c70825de55 to your computer and use it in GitHub Desktop.
DRF Dynamic Serializer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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