DRF:如何向用户详细信息api添加用户权限?

时间:2020-06-09 06:20:29

标签: django django-models django-rest-framework django-permissions

因此,我正在编写一个UserDetails视图,如下所示。

class UserDetailsView(RetrieveUpdateAPIView):
    serializer_class = AuthUserSerializer

    def get_object(self):
        return self.request.user

我的序列化器如下。

class PermissionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permission
        fields = ('id', 'name', 'codename')


class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('id', 'name')

class AuthUserSerializer(serializers.ModelSerializer):

    groups = GroupSerializer(many=True) 
    # permissions = PermissionSerializer(many=True)
    # permissions = serializers.PrimaryKeyRelatedField(many=True, queryset=Permission.objects.all())

    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'email', 
            'is_staff', 'is_active', 'is_superuser', 'last_login', 
            'date_joined', 'groups', 'user_permissions')

groups = GroupSerializer(many=True)给了我以下内容。

"groups": [
        {
            "id": 2,
            "name": "A"
        },
        {
            "id": 1,
            "name": "B"
        },
        {
            "id": 3,
            "name": "C"
        }
    ],

我期望与permissions = PermissionSerializer(many=True)类似,但出现以下错误。

Got AttributeError when attempting to get a value for field `permissions` on serializer `AuthUserSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `User` instance.
Original exception text was: 'User' object has no attribute 'permissions'. 

但是,如果直接在字段中添加user_permissions而没有添加related引用,则会为我提供所有id的权限。我也想同时拥有idnamecodename。并且,当然,找不到UserPermissions模型。 ;-(

我该如何解决?

1 个答案:

答案 0 :(得分:1)

您可以在序列化器上使用源参数。

class AuthUserSerializer(serializers.ModelSerializer):

    groups = GroupSerializer(many=True) 
    permissions = PermissionSerializer(many=True, source='user_permissions')

    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'email', 
            'is_staff', 'is_active', 'is_superuser', 'last_login', 
            'date_joined', 'groups', 'user_permissions', 'permissions')