将对象传递给序列化程序会产生序列化程序:无法获取<class'mymodel.serializers.mymodelserializer'=“”>的repr

时间:2017-12-20 22:10:56

标签: django python-3.x serialization django-rest-framework

我在调试器中收到此错误,但我从此端点获得的实际响应是正确的。当我将现有对象从DB传递给序列化程序时,我得到此错误(如下面的代码示例所示)。这是一个创建API视图,它获取POST数据,然后检查该对象是否存在于DB中。如果它确实存在则返回该对象,否则继续创建它。

class CreateMyModel(generics.ListCreateAPIView):
    serializer_class = MyModelSerializer
    queryset = MyModel.objects.all()
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,)

    def post(self, request, *args, **kwargs):
         try:
             obj = MyModel.objects.get(uuid=request.data.get('uuid'))
             serializer = self.get_serializer(obj) <-- *serializer: Unable to get repr for <class 'MyModel.serializers.MyModelSerializer'>* 
             return Response(serializer.data, status=status.HTTP_200_OK)
         except ObjectDoesNotExist:
             return self.create(request, *args, **kwargs)

class MyModel(models.Model):
    uuid = models.UUIDField(primary_key=True)
    field1 = models.TextField()
    field2 = models.ForeignKey(SomeOtherModel)

    def __str__:
       return str(self.uuid)

1 个答案:

答案 0 :(得分:0)

你真的不需要覆盖post方法。 .ListCreateAPIView有两个listcreate个动作,分别在发出请求和发布请求时触发。所以这只是需要的:

class CreateMyModel(generics.ListCreateAPIView):
     serializer_class = MyModelSerializer
     queryset = MyModel.objects.all()
     permission_classes = (IsAuthenticated,)
     authentication_classes = (JSONWebTokenAuthentication,)