Last active
February 11, 2017 12:02
-
-
Save manjitkumar/e6580296d634b0a48487 to your computer and use it in GitHub Desktop.
dynamic fields modification in django restframework serializer
This file contains hidden or 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
from rest_framework import serializers | |
class DynamicFieldsModelSerializer(serializers.ModelSerializer): | |
''' | |
A ModelSerializer that takes an additional `fields` argument that | |
controls which fields should be displayed. | |
''' | |
def __init__(self, *args, **kwargs): | |
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs) | |
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()) | |
not_to_display = existing - allowed | |
if not_to_display != existing: | |
for field_name in not_to_display: | |
self.fields.pop(field_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment