在Django Rest API中检索Serializer Method中的当前用户

时间:2016-06-27 10:06:37

标签: python django serialization django-rest-framework

我在Django Rest中有一个用户配置文件的序列化程序:

class UserProfileSerializer(serializers.ModelSerializer):
    ......................
    ......................
    status = serializers.SerializerMethodField()
    def get_status(self, obj):
        user =  self.context['request'].user
            if obj.user.userprofile in user.followed_userprofiles_set.all():
                return "following"
            else:
                return "notfollowing"
    class Meta:
        model = UserProfile
        fields = (...., 'status',...)

我有两个使用此序列化程序的视图:

class Followers(APIView):

    def get(self, request, format=None):
        #user who follow current user
        users = request.user.userprofile.followers.all()
        userprofiles= UserProfile.objects.filter(user__in=users)
        serializer = UserProfileSerializer(userprofiles, many=True)
        return Response(serializer.data)

class Friends(mixins.ListModelMixin, generics.GenericAPIView):

    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def get_queryset(self):
        .................
        .................
        return queryset

一个视图使用API​​View,另一个视图使用genericAPIView。当我从genericAPIView请求时,它正常工作。但是当我从APIView请求时,它给了我关键错误。如何在使用API​​View时检索序列化器方法中的当前用户?

1 个答案:

答案 0 :(得分:1)

由于您手动实例化UserProfileSerializer课程中的APIView而未传递context ,因此会引发KeyError异常。

request中实例化context时,您应该在UserProfileSerializer参数中传递APIView

class Followers(APIView):

    def get(self, request, format=None):
        #user who follow current user
        users = request.user.userprofile.followers.all()
        userprofiles= UserProfile.objects.filter(user__in=users)
        context = {'request':request} # prepare serializer context
        serializer = UserProfileSerializer(userprofiles, many=True, context=context) # pass context
        return Response(serializer.data)