Django REST框架:serializer上下文如何工作? [英] Django REST Framework: how serializer context works?
问题描述
在Django REST框架中,提供额外的 args
/ kwargs
到序列化程序以设置值是一个非常标准的任务的字段未通过 request.data
设置,但通过url参数或Cookie中的值。例如,我需要在POST请求时将我的注释模型的用户
字段设置为等于 request.user
。这些额外的参数被称为上下文。
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.
几个问题(, 2 )在StackOverflow上建议我覆盖我的 ModelViewSet $的
get_serializer_context()
C $ C>。我做了,没有帮助。我试图理解,出了什么问题,发现我从源代码中不明白,这个上下文系统应该是如何工作的。 (关于此事的文档也是丢失的)
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)
任何人都可以解释,在哪里serializer将上下文添加到正常的请求数据?我找到了两个地方,从中保存了值。
Can anyone explain, where serializer adds context to normal request data? I found two places, where it saves the values from context.
- serializer.save(),它将kwargs与验证的数据进行混合,但通常调用没有参数(例如通过 ModelMixins )。
- 字段。
__ new __()
,它缓存了args和kwargs,但似乎以后没有人读过。
- 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.
推荐答案
每当您使用通用视图或视图集时,DRF(3.3.2)都会添加请求
对象,视图
对象和格式
到序列化程序上下文
。您可以使用 serializer.context
访问,让我们在序列化程序中说 request.user
。
Whenever you use generic views or viewsets, DRF(3.3.2) adds request
object, view
object and format
to the serializer context
. You can use serializer.context
to access, lets say request.user
in the serializer.
当 get_serializer_class()
被调用时,这是添加的。在其中,它调用 get_serializer_context()
方法,其中所有这些参数都添加到其上下文中。
This is added when get_serializer_class()
is called. Inside that, it calls get_serializer_context()
method where all these parameters are added to its context.
DRF源代码供参考:
class GenericAPIView(views.APIView):
"""
Base class for all other generic views.
"""
def get_serializer(self, *args, **kwargs):
"""
Return the serializer instance that should be used for validating and
deserializing input, and for serializing output.
"""
serializer_class = self.get_serializer_class()
kwargs['context'] = self.get_serializer_context()
return serializer_class(*args, **kwargs)
def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}
这篇关于Django REST框架:serializer上下文如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!