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?
You need to use
partial=True
to update a row with partial data:From docs: