Created
May 29, 2017 18:26
-
-
Save gepatino/39b568138588c44e1342cbe69302e465 to your computer and use it in GitHub Desktop.
Expandable Hyperlinked Related FIelds
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 ExpandableHyperlinkedRelatedField(serializers.HyperlinkedRelatedField): | |
""" | |
Field that returns a link to the related object by default, or the whole object document if the field name | |
is provided in the comma separated argument `expand_fields`. | |
""" | |
def __init__(self, *args, **kwargs): | |
self.expand_serializer = kwargs.pop('serializer') | |
return super(ExpandableHyperlinkedRelatedField, self).__init__(*args, **kwargs) | |
def to_representation(self, obj): | |
request = self.context.get('request') | |
expand_fields = request.query_params.get('expand_fields', '').split(',') if request is not None else [] | |
if self.field_name not in expand_fields: | |
return super(ExpandableHyperlinkedRelatedField, self).to_representation(obj) | |
expand_obj = self.queryset.get(pk=obj.pk) | |
# In the NotificationSerializer, we set the 'event' as an expandable hyperlink. | |
# This means that if the argument `expand_fields=event is provided, we return | |
# the event document instead of the url. | |
# This works both in details and list resources. | |
# Additional changes required if you want to use it on writable fields. | |
class NotificationSerializer(APIV2ModelSerializer): | |
event = ExpandableHyperlinkedRelatedField(queryset=models.Event.objects.all(), | |
view_name='alerting-event-detail', | |
serializer=EventSerializer) # Add the serializer argument to the HyperlinkedRelatedField constructor | |
definition = serializers.HyperlinkedRelatedField(queryset=models.Definition.objects.all(), | |
view_name='alerting-definition-detail') | |
class Meta: | |
model = models.Notification | |
fields = '__all__' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment