我需要在request.user
函数中访问to_representation
,我尝试过self.context['request']
,但是self.context
是空字典。是否有访问request.user
的方式,或者可以将数据推送到此功能的任何方式?
def to_representation(self, obj):
print(self.context)
#output is an empty dictionary {}
更新
class RetrieveView(generics.RetrieveAPIView):
def get(self, request, *args, **kwargs):
uid = kwargs.get('uid')
try:
item = self.model.nodes.get(uid=uid)
except Exception as e:
# error response
serializer = self.serializer_class(item)
return HttpSuccessResponse(SuccessResponse(serializer.data).to_json(), status=status.HTTP_200_OK).send()
class TopicRetrieveView(single_result.RetrieveView):
model = Topic
serializer_class = topic.TopicSerializer
答案 0 :(得分:0)
所有编码均来自django rest框架通用视图generic.py
serializer_class
是我们在类定义中设置的属性,或者我们需要覆盖get_serializer_class
函数。它将在此功能中处理:
def get_serializer_class(self):
"""
Return the class to use for the serializer.
Defaults to using `self.serializer_class`.
You may want to override this if you need to provide different
serializations depending on the incoming request.
(Eg. admins get full serialization, others get basic serialization)
"""
assert self.serializer_class is not None, (
"'%s' should either include a `serializer_class` attribute, "
"or override the `get_serializer_class()` method."
% self.__class__.__name__
)
return self.serializer_class
get_serializer_class
将在get_serializer
函数中使用:
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)
和context
将由get_serializer_context
函数填充。
def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {
'request': self.request,
'format': self.format_kwarg,
'view': self
}
因此正确的用法是serializer = self.get_serializer(item)
,因为它将使用serializer_class
来序列化项目,并用可能有用的额外信息填充context
。 serializer = self.serializer_class(item)
可以仅用于序列化项目而无需更多信息。