这是我的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"}
怎么做?是否有可能这样做?
答案 0 :(得分:4)
这里的问题是serializer.data
不是实例参数,而是返回它的property
。因此,您可以通过将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