如何用序列化器实现,当admin用户请求时,序列化所有字段,但是正常的用户请求,序列化部分字段?

时间:2017-11-13 10:16:35

标签: python django django-rest-framework

如何用序列化器实现,当admin用户请求时,序列化所有字段,但是正常的用户请求,序列化Rest Framework中的部分字段?

在我的序列化器中:

class UserListSerializer(ModelSerializer):
    """
    user serializer
    """
    account = AccountSerializer(many=False, read_only=True)
    class Meta:
        model = User
        exclude = [
            'password',
        ]
...

class AccountSerializer(ModelSerializer):
    """
    user's accout
    """
    class Meta:
        model = Account
        exclude = [
            'total_charge',
            'total_consume',
        ]

在视图中:

 class UserListAPIView(ListAPIView):
    """
    the user view 
    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)
    serializer_class = UserListSerializer
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']

我的要求是当我使用普通用户请求APIView时,我想排除下面的字段:

'total_charge','total_consume'

如果我使用管理员用户请求APIView,我想序列化所有字段。

修改

我添加了get_serializer_class merhod:

class UserListAPIView(ListAPIView):
    """
    返回普通用户列表
    """
    queryset = User.objects.filter(is_admin=False, is_staff=False, is_superuser=False).exclude(status=4)

    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ['username', 'qq', 'email']
    pagination_class = UserPageNumberPagination

    class Meta:
       ordering = ['-id']

    def get_serializer_class(self):
        if self.request.user.is_superuser:
            return UserAdminListSerializer
        else:
            return UserListSerializer

    serializer_class = get_serializer_class()  # if I put this line in the front of `def get_serializer_class(self)` I will get not find error.

当我运行服务器时,它会出现问题:

追溯:

 File "/Users/xsx/Desktop/xsx/Project/xss/qiyun_admin_usermanage/api/views.py", line 40, in <module>
    class UserListAPIView(ListAPIView):
  File "/Users/xsx/Desktop/xsx/Project/xss/qiyun_admin_usermanage/api/views.py", line 59, in UserListAPIView
    serializer_class = get_serializer_class()
TypeError: get_serializer_class() missing 1 required positional argument: 'self'

1 个答案:

答案 0 :(得分:1)

您可以创建两个序列化程序并在视图中覆盖get_serializer_class

def get_serializer_class(self):
    if self.request.user.is_superuser:
        return FullAccountSerializer
    return BasicAccountSerializer