动态设置serializer和permission获取用户信息

一、用户详情的序列化

users/serializers.py

class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详情
    """
    class Meta:
        model = User
        fields = ['name', 'birthday', 'sex', 'phone', 'email']

二、users/views.py

class UserViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    """
    create:
        创建用户
    retrieve:
        用户详情
    """
    serializer_class = UserRegSerializer
    queryset = User.objects.all()
    fields = ['username', 'password', 'phone']

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        re_dict = serializer.data
        payload = jwt_payload_handler(user)
        re_dict["token"] = jwt_encode_handler(payload)
        re_dict["name"] = user.name if user.name else user.username

        headers = self.get_success_headers(serializer.data)
        return Response(re_dict, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()

    def get_permissions(self):
        """
        动态权限配置
        :return: 空列表/IsAuthenticated
        """
        if self.action == 'retrieve':
            return [IsAuthenticated()]
        return []

    def get_serializer_class(self):
        """
        动态选择序列化的方式
        :return: 序列化对象
        """
        if self.action == 'create':
            return UserRegSerializer
        return UserDetailSerializer

    def get_object(self):
        """
        获取具体的那个用户
        :return: 用户
        """
        return self.request.user

 

现在就可以从数据库获取用户的信息了

posted @ 2019-04-10 15:22  梦醒时分c  阅读(453)  评论(0编辑  收藏  举报