7

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": "[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

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 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

4 Comments

That doesn't fix it. the issue is that when I initialise UserSerializer the id is not passed into the object. It is always Nothing (or null)
@ISAIMobile By calling User() you're creating a new user object. To update an already present user fetch that user using a User.objects.get query first and then pass that to the serializer with partial=True.
Thanks for that, but how do I extract the id of the user from request.DATA?
@ISAIMobile request.DATA['id'] should do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.