我试图使用方法put并使用get_object与RetrieveUpdateAPIView使用令牌返回用户模型实例的更改。但是我只得到用户数据:
{
"id": int,
"username": "",
"email": "",
"is_staff": bool
}
有办法得到这样的吗?:
{
"user": {
"id": int,
"username": "",
"email": "",
"is_staff": bool
},
"token": ""
}
这是为了不改变前端的逻辑;获取授权令牌:user.token
这是我的序列化器:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'is_staff')
这是我的viewset:
class UserAPI(generics.RetrieveUpdateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = UserSerializer
def get_object(self):
return self.request.user
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'is_staff')
class UserAPI(generics.RetrieveUpdateAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = UserSerializer
def get_object(self):
return self.request.user
serializer_class = LoginUserSerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
token = AuthToken.objects.create(user)[1]
return Response({"user": UserSerializer(user,
context=self.get_serializer_context()).data,
"token": token })