django rest framework - always INSERTs, never UPDA

2019-03-20 15:13发布

问题:

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

View Code:

JSON POSTED:

{
    "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' , )

Model

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

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

回答1:

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

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

From docs:

By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the partial argument in order to allow partial updates.