django drf 统一处理操作人和时间字段

场景

如果你的表结构有这些字段:创建人/创建时间/更新人/更新时间/删除人/删除时间,我们可以统一处理这些字段的更新和插入,而不需要额外显示操作。

代码

1.ActionViewSetMixin:

python 复制代码
import datetime
from rest_framework import status
from rest_framework.response import Response



class ActionViewSetMixin:

   def destroy_mixin(self, request):
       instance = self.get_object()
       data = {
           "deleted_by": request.user.username,
           "deleted_at": datetime.datetime.now(),
           "is_deleted": True,
       }
       serializer = self.get_serializer(instance, data=data, partial=True)
       serializer.is_valid(raise_exception=True)
       self.perform_update(serializer)

       if getattr(instance, "_prefetched_objects_cache", None):
           # If 'prefetch_related' has been applied to a queryset, we need to
           # forcibly invalidate the prefetch cache on the instance.
           instance._prefetched_objects_cache = {}

       return Response(serializer.data)

   def destroy(self, request, *args, **kwargs):
       return self.destroy_mixin(request)

   def update_mixin(self, request, serializer):
       serializer.is_valid(raise_exception=True)
       data = serializer.validated_data
       data["updated_by"] = request.user.username
       data["updated_at"] = datetime.datetime.now()
       partial = True
       instance = self.get_object()
       serializer = self.get_serializer(instance, data=data, partial=partial)
       serializer.is_valid(raise_exception=True)
       self.perform_update(serializer)

       if getattr(instance, "_prefetched_objects_cache", None):
           # If 'prefetch_related' has been applied to a queryset, we need to
           # forcibly invalidate the prefetch cache on the instance.
           instance._prefetched_objects_cache = {}

       return Response(serializer.data)

   def update(self, request, *args, **kwargs):
       serializer_class = kwargs.pop("serializer", self.get_serializer)
       return self.update_mixin(request, serializer_class(data=request.data))

   def create_mixin(self, request, *args, **kwargs):
       data = request.data.copy()
       data["created_by"] = request.user.username
       data["created_at"] = datetime.datetime.now()
       serializer_class = kwargs.pop("serializer", self.get_serializer)
       serializer = serializer_class(data=data)
       serializer.is_valid(raise_exception=True)
       self.perform_create(serializer)
       headers = self.get_success_headers(serializer.data)
       return Response(
           serializer.data, status=status.HTTP_201_CREATED, headers=headers
       )

   def create(self, request, *args, **kwargs):
       return self.create_mixin(request, *args, **kwargs)

2.APIModelViewSet继承ModelViewSet和ActionViewSetMixin:

python 复制代码
from rest_framework.viewsets import ModelViewSet

from common.drf.mixins import ActionViewSetMixin, ResponseMixin


class APIModelViewSet(ActionViewSetMixin, ResponseMixin, ModelViewSet):
   extra_permissions = []  # 不覆盖默认的权限
   action_extra_permission_mapping = {}

   def parse_page_params(self):
       if self.request.method == "GET":
           page = self.request.query_params.get("page", 1)
           page_size = self.request.query_params.get("page_size", 10)
       else:
           page = self.request.data.get("page", 1)
           page_size = self.request.data.get("page_size", 10)
       try:
           return int(page), int(page_size)
       except Exception as e:
           return 1, 10

   def get_permissions(self):
       permissions = super(APIModelViewSet, self).get_permissions()

       extra = [x() for x in self.extra_permissions]
       action = self.action_extra_permission_mapping.get(self.action, [])
       return permissions + extra + [p() for p in action]

   @classmethod
   def get_validated_params(cls, serializer, params):
       s = serializer(data=params)
       s.is_valid(raise_exception=True)
       return s.validated_data

3.视图类继承APIModelViewSet:

python 复制代码
class ScanRecordViewSet(APIModelViewSet):
   queryset = models.ScanRecord.exclude_deleted_objects.all()
   serializer_class = serializers.ScanRecordSerializer
   pagination_class = DataPageNumberPagination
   filter_backends = [CustomFilterBackend, SearchFilter]

   search_fields = ["status", "mode", 'risk']
   custom_query_fields = ["status", "mode", "risk"]
相关推荐
CSXB999 分钟前
三十四、Python基础语法(文件操作-上)
开发语言·python·功能测试·测试工具
亚图跨际1 小时前
MATLAB和Python及R潜变量模型和降维
python·matlab·r语言·生物学·潜变量模型
infiniteWei1 小时前
【Lucene】全文检索 vs 顺序扫描,为何建立索引比逐个文件搜索更高效?
django·全文检索·lucene
IT古董1 小时前
【机器学习】决定系数(R²:Coefficient of Determination)
人工智能·python·机器学习
德育处主任Pro1 小时前
『Django』APIView基于类的用法
后端·python·django
Star Patrick1 小时前
算法训练(leetcode)二刷第十九天 | *39. 组合总和、*40. 组合总和 II、*131. 分割回文串
python·算法·leetcode
武子康2 小时前
大数据-213 数据挖掘 机器学习理论 - KMeans Python 实现 距离计算函数 质心函数 聚类函数
大数据·人工智能·python·机器学习·数据挖掘·scikit-learn·kmeans
写点什么啦2 小时前
使用R语言survminer获取生存分析高风险和低风险的最佳截断值cut-off
开发语言·python·r语言·生存分析·x-tile
武子康2 小时前
大数据-214 数据挖掘 机器学习理论 - KMeans Python 实现 算法验证 sklearn n_clusters labels
大数据·人工智能·python·深度学习·算法·机器学习·数据挖掘
封步宇AIGC3 小时前
量化交易系统开发-实时行情自动化交易-Okex K线数据
人工智能·python·机器学习·数据挖掘