通过Django Rest Framework视图调用模型方法

时间:2018-06-23 14:29:11

标签: django django-models django-rest-framework

我有一个模特:

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

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

我为此有一个简单的序列化器:

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

如何使用DRF从我的观点调用plus_one模型方法? 这是如何可调用的,什么是良好实践?谢谢!

添加:

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

2 个答案:

答案 0 :(得分:2)

如果我理解的正确,那么每次对象更新时都需要调用plus_one。在这种情况下,您可以像这样重写perform_update()方法:

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

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

答案 1 :(得分:1)

这应该在您的SizeAPIView保持不变的情况下在序列化程序级别完成:

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