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
函数始终返回None
。当我调试它时,我发现self.context是空字典,即{}
。要确保我还打印了self.context.keys()
,还是它的空列表。
我跟着这个帖子。
Get current user in Model Serializer
PS:我正在使用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)
答案 0 :(得分:26)
如何在视图集的list()
方法中创建序列化程序?你应该打电话给
serializer = self.get_serializer(data=request.data)
在default implementation of this method in DRF mixins中完成后自动填充序列化程序上下文。但我觉得你只是手动创建它,如下所示:
serializer = MyModelSerializer(instance)
因此,要解决此问题,您应该调用get_serializer()
,或者将额外的上下文参数传递给序列化器构造函数:
serializer = MyModelSerializer(instance, context={'request': request, ...})
答案 1 :(得分:0)
我们可以在序列化程序中使用self._context
来访问request
和view
。
class MyModelSerializer(serializers.ModelSerializer):
field1 = serializers.CharField()
field2 = serializers.SerializerMethodField('get_current_user')
def get_current_user(self):
request = self._context.get("request")
if request and hasattr(request, "user"):
return request.user
return None