问题描述
class MyModelSerializer(serializers.ModelSerializer):
field1 = serializers.CharField()
field2 = serializers.SerializerMethodField('get_awesome_user')
def get_current_user(self):
request = self.context.get("request")
if request and hasattr(request, "user"):
return request.user
return None
def get_awesome_user(self, obj):
user = self.get_current_user()
## use this user object, do some stuff and return the value
return ...
我的api(使用 authentication_classes
和 permission_classes
)正在使用此序列化程序,并且 get_current_user
函数始终返回无
。调试时,我发现self.context是空字典,即 {}
。可以肯定的是,我还打印了 self.context.keys()
,但它仍然是空列表。
My api(which uses authentication_classes
and permission_classes
) is using this serializer and the get_current_user
function always returns None
. when I debug it, I found that self.context is empty dictionary, i.e {}
. to be double sure I also printed self.context.keys()
, still it's empty list.
我关注了
PS:我正在使用 djangorestframework == 3.3.3
, Django == 1.9.1
PS: I'm using djangorestframework==3.3.3
, Django==1.9.1
编辑:添加视图集代码
class MyModelViewSet(viewsets.ModelViewSet):
authentication_classes = (SessionAuthentication, BasicAuthentication, TokenAuthentication)
permission_classes = (IsAuthenticated,)
def list(self, *args, **kwargs):
queryset = MyModel.objects.all()
page = self.paginate_queryset(queryset)
if page is not None:
serializer = MyModelSerializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = MyModelSerializer(queryset, many=True)
return Response(serializer.data)
推荐答案
如何在视图集的 list()
方法中创建序列化器?您应该致电
How do you create serializer in your viewset's list()
method? You should call
serializer = self.get_serializer(data=request.data)
可以自动填充序列化程序上下文,就像在。但是,我觉得您只是在手动创建它,就像这样:
to get your serializer context filled automatically as it is done in default implementation of this method in DRF mixins., but I have a feeling that you're just creating it manually, like this:
serializer = MyModelSerializer(instance)
因此,要解决此问题,您应该调用 get_serializer()
,或将额外的上下文参数传递给序列化程序构造函数:
So, to fix this, you should either call get_serializer()
, or pass extra context argument to serializer constructor:
serializer = MyModelSerializer(instance, context={'request': request, ...})
这篇关于Django Rest Framework-self.context没有请求属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!