django休息框架 - 总是INSERT,永远不会更新

时间:2014-01-28 17:16:26

标签: python django rest frameworks django-rest-framework

我希望能够通过POST更新用户记录。但是,id始终为NULL。即使我通过了id,它也似乎被忽略了

查看代码:

JSON张贴:

{
    "id": 1, 
    "name": "Craig Champion", 
    "profession": "Developer", 
    "email": "craig@isai.co.uk"
}

@api_view(['POST'])
def get_purchase(request):
    """
    Gets purchase records for a user

    Purchase collection is returned
    """

    user = User();
    serializer = UserSerializer(user, data=request.DATA)

    if serializer.is_valid():

       #The object ALWAYS has ID = nothing at this point

        serializer.save()

        return Response(serializer.data, status=status.HTTP_200_OK)

    else:
        return Response(serializer.errors,   status=status.HTTP_400_BAD_REQUEST)

ModelSerializer

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('id', 'name', 'profession', 'email', 'password', )
        write_only_fields = ('password' , )

模型

class User(models.Model):
    name = models.CharField(max_length=30, null=True, blank=True)
    profession = models.CharField(max_length=100, null=True, blank=True)
    email = models.EmailField()
    password = models.CharField(max_length=20, null=True, blank=True)


    def __unicode__(self):
        return self.name

如何强制保存更改更新并查看ID?

1 个答案:

答案 0 :(得分:12)

您需要使用partial=True更新包含部分数据的行:

serializer = UserSerializer(user, data=request.DATA, partial=True)

来自docs

  

默认情况下,必须为所有必填字段传递序列化程序的值   或者他们会抛出验证错误。您可以使用partial参数   为了允许部分更新。