[Django]-Calling Model Method Via Django Rest Framework View

3👍

If I understood you right you need to call plus_one each time when object updated. In this case you can override perform_update() method like this:

class SizeAPIView(generics.UpdateAPIView):
    serializer_class = SizeSerializer
    queryset = Size.objects.filter()

    def perform_update(self, serializer):
        serializer.save()
        serializer.instance.plus_one()

2👍

This should be done on serializer level while your SizeAPIView remains unchanged:

class SizeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Size
        fields = '__all__'

    def update(self, instance, validated_data):

        for attr, value in validated_data.items():
            setattr(instance, attr, value)

        instance.plus_one()  # performs `instance.save` too.

Documentation on saving instances.

👤mrehan

Leave a comment