django休息补丁,如何保存更新的数据?

时间:2018-03-15 22:07:17

标签: django django-rest-framework

对于REST PATCH,我想更新已存在的模型中的某些值并将其保存回来。但是,我显然在这里错过了一些步骤:

  1. 找到要更新的项目
  2. 更新值
  3. 保存
  4. 看起来很简单:

    ~/.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().'"

    有人能指出我如何解开这个结?

1 个答案:

答案 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 )