4

I have a model:

class Size(models.Model):
    size = models.DecimalField(max_digits=5, decimal_places=1)

    def plus_one(self):
        self.size += 1
        self.save()

And I have a simple serializer for this:

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

How can I call a plus_one model method from my view, using DRF? How is it callable, what is good practice for that? Thanks!

Added:

class SizeAPIView(generics.UpdateAPIView):
    serializer_class = SizeSerializer
    queryset = Size.objects.filter()
2
  • 1
    Can you show your view? Commented Jun 23, 2018 at 14:31
  • @neverwalkaloner made, but this is just abstaract Commented Jun 23, 2018 at 14:37

2 Answers 2

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()
Sign up to request clarification or add additional context in comments.

3 Comments

What is about best practice? Is it good, when i create adittional ready_for_plus bool field in Model and add if ready_for_plus = True to plus_one method? Idea is to give access to method from API request. Anyway thank, you make it clear, again:).
@D.Make you are welcome. Not sure but probably it would be better to override model's save() method. In this case you will not required doubled save operation.
got it, so i will do, tnx!
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.

Comments

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.