Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django rest framework - always INSERTs, never UPDATES

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?

like image 320
Craig Champion Avatar asked Jan 28 '14 17:01

Craig Champion


1 Answers

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.

like image 108
Ashwini Chaudhary Avatar answered Sep 23 '22 03:09

Ashwini Chaudhary