我的列表,检索和销毁操作按预期工作。
HTTP响应= 201“已创建”
addEventHandler
在ViewSet内
override fun doPost(request: HttpServletRequest, response: HttpServletResponse) {
response.contentType = "image/png"
response.status = HttpServletResponse.SC_OK
val diff = ImgDiff.getDifference("img1", "img2", tolerance)
response.addHeader("diff", diff.toString())
ImageIO.write(ImageIO.read(File("diffedFile.png")), "PNG", response.outputStream)
}
这是我运行"POST /api/atoms/?uid=04d38ad99b2a4353a18438c651eac5ab&created_at=2019-05-12T22:30:04.725089Z&updated_at=2019-05-12T22:30:07.053148Z&charge=1&mass=2 HTTP/1.1" 201 152
时得到的信息
class AtomViewSet(viewsets.ViewSet):
def create(self, request):
serializer = AtomSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
# True
serializer.save()
# self.perform_create(serializer) # doesn't work
# self.node.save() # doesn't work
# headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,) # headers=headers
尽管鼓励保存输出,但是奇怪的是资源没有保存到数据库中。
我正在针对非模型模型使用ViewSets和自定义序列化程序。
serializer.save()
序列化器
<Atom: {'uid': '04d38ad99b2a4353a18438c651eac5qq', 'created_at': datetime.datetime(2019, 5, 12, 22, 30, 4, 725089, tzinfo=<UTC>), 'updated_at': datetime.datetime(2019, 4, 12, 22, 30, 7, 53148, tzinfo=<UTC>), 'charge': 0.0, 'mass': 1.0}>
我正在看我的序列化器。不确定创建和更新应该包含什么
http://www.cdrf.co/3.1/rest_framework.serializers/Serializer.html
答案 0 :(得分:1)
在您的AtomSerializer
中,您实际上并没有保存对象,只是在内存中创建或修改了它的实例,请使用save()
将实例持久保存到数据库中。
def create(self, validated_data):
atom = Atom(**validated_data)
atom.save()
# Alternative you could use atom = Atom.objects.create(**validated_data)
return atom
同样,您的更新方法也需要在修改后保存对象。
def update(self, instance, validated_data):
for field, value in validated_data.items():
setattr(instance, field, value)
instance.save() # <-- saving the instance after setattr
return instance