jonalv
jonalv

Reputation: 6126

Clarification needed for `Including extra context` to a serializer in Django REST Framework

According to: https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context

I can write:

serializer = AccountSerializer(account, context={'request': request})

and then serializer.data will look like:

# {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}

but it doesn't say how I am to implement it. I mean it must be based on a call to rest_framework.reverse a bit like in this example:

class CompleteTaskModelSerializer(rest_serializers.ModelSerializer):

    resultLocation = rest_serializers.SerializerMethodField()

    class Meta:
        model = TaskModel
        fields = ('id', 'resultLocation')

    def get_resultLocation(self, obj):
        return reverse('model', obj.model, request=request)

but it won't acknowledge that there is anything called request in my method get_resultLocation. How is this magic supposed to work?

Upvotes: 1

Views: 53

Answers (1)

Nico Griffioen
Nico Griffioen

Reputation: 5405

In the same docs, it also says:

The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.

So I would guess the example class could be changed to work like this

class CompleteTaskModelSerializer(rest_serializers.ModelSerializer):

    resultLocation = rest_serializers.SerializerMethodField()

    class Meta:
        model = TaskModel
        fields = ('id', 'resultLocation')

    def get_resultLocation(self, obj):
        return reverse('model', obj.model, request=self.context['request'])

Upvotes: 1

Related Questions