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

DRF : how to add user permissions to user detail api?

所以我写了一个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 模型。 ;-(

我该如何解决这个问题?

您可以在 Serializer 上使用 source 参数。

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')