如何使用Django Rest Framwork Serializer更新数据库中的模型失败?

时间:2017-08-03 15:36:23

标签: python django django-rest-framework

如果我是第一次运行我的代码,它会成功运行。数据存储在数据库中,http代码为200.如果我在客户端更改了某些数据并尝试再次保存模型,则会出现以下错误。

我在django doc上读过,我可以使用另存为"创建"和"更新"同样。

错误消息

heating mapping with this zone already exists

views.py

from heatingControll.models import  HeatingMapping as HeatingMappingModel
 # ... some code ...
    @detail_route(methods="post")
    def save(self, request):
        zone = request.data.get('zone')
        data = json.loads(zone)

        serializer = HeatingMappingSerializer(data=data)

        valid = serializer.is_valid(raise_exception=True)
        if(valid):
           result = serializer.save()
           self.response = {"result": True, "data":HeatingMappingSerializer(result).data, "message": "Erfolgreich gespeichert"}

        return JsonResponse(self.response, safe=False)

zaidfazil支持的解决方案

@detail_route(方法="后&#34) def save(self,request):     zone = request.data.get(' zone')     data = json.loads(zone)

if 'zone' in data:
    obj = HeatingMappingModel.objects.get(id=data.get('id'))
    serializer = HeatingMappingSerializer(data=data, instance=obj)
else:
    serializer = HeatingMappingSerializer(data=data)

valid = serializer.is_valid(raise_exception=True)
if(valid):
   result = serializer.save()
   self.response = {"result": True, "data":HeatingMappingSerializer(result).data, "message": "Erfolgreich gespeichert"}

return JsonResponse(self.response, safe=False)

1 个答案:

答案 0 :(得分:0)

尝试编辑您的视图,可能是这样,

@detail_route(methods="post")
def save(self, request, pk):
    zone = request.data.get('zone')
    data = json.loads(zone)
    obj = HeatingMapping.objects.get(pk=pk)

    serializer = HeatingMappingSerializer(data=data, instance=obj)

    valid = serializer.is_valid(raise_exception=True)
    if(valid):
       result = serializer.save()
       self.response = {"result": True, "data":HeatingMappingSerializer(result).data, "message": "Erfolgreich gespeichert"}

    return JsonResponse(self.response, safe=False)