Consider:
class CustomSerializerField(serializers.Field):
def to_representation(self, obj):
return obj
def to_internal_value(self, data):
# How can I access the request object here?
return {}
And now the ModelSerializer
class SomeModelSerializer(serializers.ModelSerializer):
some_field = CustomerSerializerField()
class Meta:
model = SomeModel
fields = ('__all__', )
I have tried
self.request.user
DRF is passing the outer contexts to nested levels during the execution. In your case, the SomeModelSerializer
class passes all the context it took (from the view, probably) to its fields and "nested serializers"
To access the request
variable in CustomerSerializerField
, just use,
user = self.context['request'].user
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With