It's a pretty standard task in Django REST Framework to supply additional args
/kwargs
to a serializer to set values of fields set not via request.data
, but via the value in url parameters or cookies. For instance, I need to set user
field of my Comment model equal to request.user
upon POST request. Those additional arguments are called context.
Several questions (1, 2) on StackOverflow suggest that I override get_serializer_context()
method of my ModelViewSet
. I did and it doesn't help. I tried to understand, what's wrong, and found out that I don't understand from the source code, how this context system is supposed to work in general. (documentation on this matter is missing, too)
Can anyone explain, where serializer adds context to normal request data? I found two places, where it saves the values from context.
- serializer.save(), method, which mixes kwargs with validated data, but it is usually called with no arguments (e.g. by ModelMixins).
- fields.
__new__()
, which caches args and kwargs, but it seems that nobody ever reads them later.