本文介绍了django休息框架 - 永远是INSERT,永远不会UPDATES的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过POST更新用户记录。但是,id始终为NULL。即使我传递id似乎被忽略

I want to be able to UPDATE a user record by POST. However, the id is always NULL. Even if I pass the id it seems to be ignored

查看代码:

JSON POSTED:

JSON POSTED:

{
    "id": 1,
    "name": "Craig Champion",
    "profession": "Developer",
    "email": "[email protected]"
}

@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

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?

How can I force the savechanges to update and see the ID?

推荐答案

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

You need to use partial=True to update a row with partial data:

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

从:

这篇关于django休息框架 - 永远是INSERT,永远不会UPDATES的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 22:17