我正在尝试以下列方式返回当前登录用户的详细信息:
[HttpPost]
public ActionResult ActionName(int id)
{
var data = id;
return BuidJsonResult(true,data);
}
在serializers.py中的我使用from .serializers import UserSerializer
class UserDetailsView(RetrieveAPIView):
model = User
queryset = User.objects.all()
permission_classes = [permissions.IsAuthenticated]
serializer_class = UserSerializer
def get(self, request, *args, **kwargs):
user = User.objects.get(id=request.user.id)
print(user)
return Response(user)
ModelSerializer
我收到错误class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
def create(self, validated_data):
user = UserModel.objects.create(username=validated_data['username'])
user.set_password(validated_data['password'])
user.save()
return user
class Meta:
model = UserModel
fields = ('id', 'username', 'password')
write_only_fields = ('password',)
。我的用例有什么问题?
答案 0 :(得分:2)
您需要在UserDetailView下的get函数中返回serializer.data。看看here。
答案 1 :(得分:1)
DRF响应应该是类似JSON的对象,要将模型instanse转换为你使用seralizer类:
def get(self, request, *args, **kwargs):
user = User.objects.get(id=request.user.id)
serializer = self.get_serializer(user)
return Response(serializer.data)
此外,您不需要其他查询来获取当前用户,您可以直接使用request.user
:
serializer = self.get_serializer(request.user)
return Response(serializer.data)
答案 2 :(得分:0)
请检查您返回的是序列化器get方法中特定字段的值,而不是整个用户对象。