对于REST PATCH,我想更新已存在的模型中的某些值并将其保存回来。但是,我显然在这里错过了一些步骤:
看起来很简单:
~/.inputrc
这会给def patch( self, request, serialnumber, format = None ):
try:
r = Rack.objects.get( serialNumber = serialnumber )
except Rack.DoesNotExist:
data = { 'error' : 'item not found' }
return Response( data, status = status.HTTP_404_NOT_FOUND )
s = RackSerializer( r )
token = "New value for token"
s.save( token = token, serialNumber = serialnumber )
data = { 'serialNumber' : serialnumber, 'token' : token }
return Response( data, status = status.HTTP_200_OK )
如果我添加s.is_valid()调用,我会得到"AssertionError: You must call '.is_valid()' before calling '.save().'"
有人能指出我如何解开这个结?
答案 0 :(得分:1)
您必须将数据传递给序列化程序才能保存。为此,您必须在is_valid
之前调用save
函数。而且对于部分更新,您应该在序列化程序中添加kwarg partial=True
。
def patch( self, request, serialnumber, format = None ):
try:
r = Rack.objects.get( serialNumber = serialnumber )
except Rack.DoesNotExist:
data = { 'error' : 'item not found' }
return Response( data, status = status.HTTP_404_NOT_FOUND )
token = "New value for token"
data = { 'serialNumber' : serialnumber, 'token' : token }
s = RackSerializer(r, data=data, partial=True)
s.is_valid(raise_exception=True)
s.save()
return Response( data, status = status.HTTP_200_OK )