[Django]-Django Rest Framework update field

44👍

The definition of what methods the endpoint can accept are done in the view, not in the serializer.

The update method you have under your serializer needs to be moved into your view so you’ll have something like:

serializers.py

class ClientNameSerializer(serializers.ModelSerializer):
    class Meta:
        model = ClientUser

views.py

class UpdateName(generics.UpdateAPIView):
    queryset = ClientUser.objects.all()
    serializer_class = ClientNameSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.name = request.data.get("name")
        instance.save()

        serializer = self.get_serializer(instance)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        return Response(serializer.data)

Take note that you’re overriding the UpdateModelMixin and you might need to change the above code a little bit to get it right.

6👍

One other approach might be the following one:

serializer.py

class ClientNameSerializer(serializers.ModelSerializer):
   class Meta:
        model = ClientUser
        fields = ('name',)

   def update(self, instance, validated_data): 
        instance.name = validated_data.get('name', instance.name)
        instance.save()
        return instance

views.py

class UpdateName(generics.UpdateAPIView):
    queryset = ClientUser.objects.all()
    serializer_class = ClientNameSerializer
    permission_classes = (permissions.IsAuthenticated,)

    def update(self, request, *args, **kwargs):
        data_to_change = {'name': request.data.get("name")}
        # Partial update of the data
        serializer = self.serializer_class(request.user, data=data_to_change, partial=True)
        if serializer.is_valid():
            self.perform_update(serializer)

        return Response(serializer.data)

5👍

If you use class UpdateName(generics.CreateAPIView), this will only call a create() method on the serializer.

You should subclass generics.UpdateAPIView instead. And that’s it.
You do not have to move your method to the view as suggested in this answer (it is basically copying/duplicating the UpdateModelMixin’s update method)

For more information how serializers work regarding saving/updating see the docs here:

Leave a comment