如果我是第一次运行我的代码,它会成功运行。数据存储在数据库中,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)
答案 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)