Django 休息框架将字典添加到序列化程序

Django rest framework add dict to serializer

这是我的 serializers.py:

class SysUserSerializer(serializers.ModelSerializer):
    pk = serializers.IntegerField(read_only=True)
    login_id = serializers.CharField(required=False)
    name = serializers.CharField(required=False)

    class Meta:
        model = SysUser
        fields = ('pk','login_id','name')

这是我的 views.py:

class GetUserDetail(APIView):
    def get(self, request, format=None):
        sysuser = SysUser.objects.get(id=1)
        serializer = SysUserSerializer(sysuser)
        serializer.data['gender'] = 'male' # i don't think this line is working
        return Response(serializer.data, status=200)

但我收到了这样的回复:

{"pk": 1, "login_id": "john77", "name": "John"}

我想要这样的回复:

{"pk": 1, "login_id": "john77", "name": "John", "gender": "male"}

如何实现?可以这样做吗?

这里的问题是 serializer.data 不是实例参数,而是 property 而 returns 它。所以你可以通过将 serializer.data 分配给变量来解决这个问题。

class GetUserDetail(APIView):
    def get(self, request, format=None):
        sysuser = SysUser.objects.get(id=1)
        serializer = SysUserSerializer(sysuser)
        data = serializer.data
        data['gender'] = 'male'
        return Response(data, status=200)

你也可以在validate序列化器

方法中将数据分配给serializer.data