Reputation: 544
The documentation states:
You can provide arbitrary additional context by passing a
context
argument when instantiating the serializer.
Ok, so let's do that:
serializer = AccountSerializer(account, context={'foo':'bar'})
The documentation then states:
The context dictionary can be used within any serializer field logic by accessing the
self.context
attribute.
Ok, so let's do that:
class AccountSerializer(serializers.ModelSerializer):
custom_field = serializers.SerializerMethodField()
class Meta:
model = Account
fields = ('id', 'name', 'custom_field')
def get_custom_field(self, obj):
print('Context:', self.context)
foo = self.context.get('foo')
print('Foo:', foo)
...
return "custom data"
Those print statements result in:
Context: {'request': <rest_framework.request.Request object at 0x1127d3160>, 'format': None, 'view': <account.api.views.AccountView object at 0x1127c4f98>
Foo: None
What am I doing wrong here? No matter what the context is not modified with the extra context desired.
Upvotes: 4
Views: 7222
Reputation: 20986
You are showing the result of the serializer being used in the DRF GenericAPIView. The get_serializer_context method by default provides the context entries 'request', 'view' and 'format' and the context argument of the serializer constructor is ineffective. If you want to add more things to the context there, you also need to override it in the view:
def get_serializer_context(self):
context = super().get_serializer_context()
context['foo'] = 'bar'
return context
Upvotes: 6