【问题标题】:How to add a Reason for Deletion to all DRF Delete APIs如何为所有 DRF 删除 API 添加删除原因
【发布时间】:2017-07-01 10:22:34
【问题描述】:

在使用Django Simple History 跟踪模型更改的Django Rest Framework 应用程序中,如何强制用户为所有Destroy End Points 传递Reason for Deletion,然后将该原因传递给Django Simple History 的Change Reason

另外,对于具有删除级联的相关模型,该原因是否会传递给相关的已删除条目?

更新:

尝试在another question here on SO 之后覆盖以下销毁方法。问题是,changeReason(即history_change_reason)在删除后位于哪里?我以为这将是历史表中的一列?但是,它不存在所以即使下面的代码正在运行,我也找不到保存原因的位置。

class DeleteViewSet(mixins.DestroyModelMixin):
    def destroy(self, request, *args, **kwargs):
        try:
            if 'delete_reason' not in request.data.keys():
                return Response(status=status.HTTP_400_BAD_REQUEST,data='{delete_reason: Invalid Delete Reason}')
            else:
                instance = self.get_object()
                instance.changeReason = request.data['delete_reason']
                instance.save()
                self.perform_destroy(instance)
        except Http404:
            pass
        return Response(status=status.HTTP_204_NO_CONTENT)

缺少历史更改原因列:

我在所有历史记录表中看到的唯一history_* 是:

1. history_id
2. history_date
3. history_type
4. history_user_id

我在任何历史记录表中都找不到history_change_reason

【问题讨论】:

    标签: django django-rest-framework django-simple-history


    【解决方案1】:

    好的。找到了我的两个问题的答案。

    缺少历史更改原因列:

    这是一个版本问题。 pip3.6 install --upgrade django-simple-history 然后 migrate 解决了这个问题。

    作为 Mixin 的删除原因:

    这通过检查是否提供了deletion_reason来工作。

    class DeleteViewSet(mixins.DestroyModelMixin):
        def destroy(self, request, *args, **kwargs):
            try:
                if 'delete_reason' not in request.data.keys():
                    return Response(status=status.HTTP_400_BAD_REQUEST,data='{delete_reason: Invalid Delete Reason}')
                else:
                    instance = self.get_object()
                    instance.changeReason = request.data['delete_reason']
                    # instance.save()  ==>Don't do this because it will cause a second instance to be saved in the history tables
                    self.perform_destroy(instance)
            except Http404:
                pass
            return Response(status=status.HTTP_204_NO_CONTENT)
    

    未解决:

    当模型之间的关系中有 delete_cascade 时,将 deletion_reason 传递给随后被删除的所有表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2012-05-21
      • 1970-01-01
      • 2022-08-14
      • 2017-02-13
      • 2016-05-15
      • 1970-01-01
      相关资源
      最近更新 更多