Skip to content

Instantly share code, notes, and snippets.

@gepatino
Created May 29, 2017 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gepatino/bfef5710a4c10d4a2b32d568e95edc3f to your computer and use it in GitHub Desktop.
Save gepatino/bfef5710a4c10d4a2b32d568e95edc3f to your computer and use it in GitHub Desktop.
Serializer with `extra_fields` option: add fields from the query arguments
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