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()
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With