-
-
Save AndrewJHart/efef060664b5c1541784 to your computer and use it in GitHub Desktop.
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 DynamicFieldsMixin(object): | |
""" | |
A serializer mixin that takes an additional `fields` argument that controls | |
which fields should be displayed. | |
Usage:: | |
class MySerializer(serializers.HyperlinkedModelSerializer, DynamicFieldsMixin): | |
class Meta: | |
model = MyModel | |
""" | |
def __init__(self, *args, **kwargs): | |
super(DynamicFieldsMixin, 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()) | |
for field_name in existing - allowed: | |
self.fields.pop(field_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment