如何设置DestroyAPIView方法不是真正删除我的实例?

时间:2018-01-08 10:47:31

标签: python django django-rest-framework

我有一个模型,如下:

class BModel(models.Model):
    name = models.CharField(max_length=11)
    status = models.CharField(default="is_active")  # if delete:  deleted
    a = models.ForeignKey(AModel)

    def delete(self, using=None, keep_parents=False):
        pass  # there I want to set the BModel's status to `deleted`

串行:

class BModelSerializer(ModelSerializer):
    class Meta:
        model = BModel
        fields = "__all__"

其观点如下:

class BModelListAPIView(ListAPIView):
    serializer_class = BModelSerializer
    permission_classes = []
    queryset = BModel.objects.all()

class BModelDestroyAPIView(DestroyAPIView):
    serializer_class = BModelSerializer
    permission_classes = []
    queryset = BModel.objects.all()

我的要求是当使用Django-Rest-Framework删除我的BModel时,我想将BModel的状态字段设置为deleted,而不是真正删除实例。如何访问它?

当我尝试将删除方法写入我的模型时,会出现默认的删除方法:

def delete(self, using=None, keep_parents=False):

我对此有一些疑问: 这是针对BModel的实例吗? 是否应该通过delete方法来访问我的要求?

1 个答案:

答案 0 :(得分:0)

DestroyAPIViewperform_destroy方法。您可以覆盖它并添加删除逻辑。例如:

class BModelDestroyAPIView(DestroyAPIView):
    serializer_class = BModelSerializer
    permission_classes = []
    queryset = BModel.objects.all()

    def perform_destroy(self, instance):
        instance.delete_flag = True
        instance.save()

delete的{​​{1}}方法将覆盖默认的删除方法。哪个也会影响Django Admin。您还可以向该模型的Manager添加自定义删除方法。 Refer