The documentation states:
You can provide arbitrary additional context by passing a
contextargument 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.contextattribute.
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.