Created
May 29, 2017 19:11
-
-
Save gepatino/bfef5710a4c10d4a2b32d568e95edc3f to your computer and use it in GitHub Desktop.
Serializer with `extra_fields` option: add fields from the query arguments
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
class DefinitionSerializer(UserRelatedSerializer): | |
extra_fields = ('unread_notifications_count',) | |
def __init__(self, *args, **kwargs): | |
""" | |
Redefine __init__ to add extra_fiels feature. | |
You must add the field name to self.extra_fields, and add a method | |
`get_field_name` since internally this serialzier creates a | |
SerializerMethodField for each extra_field that is also in the | |
'extra_fields' query_param. | |
""" | |
res = super(APIV2ModelSerializer, self).__init__(*args, **kwargs) | |
request = self.context.get('request') | |
if self.extra_fields and request: | |
extra_fields = request.query_params.get('extra_fields', '').split(',') | |
for field in extra_fields: | |
if field in self.extra_fields: | |
self.fields[field] = serializers.SerializerMethodField() | |
return res | |
def get_unread_notifications_count(self, obj): | |
return obj.notifications.filter(unread=True).count() | |
class Meta: | |
model = models.Definition | |
fields = '__all__' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment