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

news/2024/10/4 7:43:40/

场景

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

代码

1.ActionViewSetMixin:

python">import datetime
from rest_framework import status
from rest_framework.response import Responseclass 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_datadata["updated_by"] = request.user.usernamedata["updated_at"] = datetime.datetime.now()partial = Trueinstance = 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.usernamedata["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 ModelViewSetfrom common.drf.mixins import ActionViewSetMixin, ResponseMixinclass 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, 10def 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]@classmethoddef 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.ScanRecordSerializerpagination_class = DataPageNumberPaginationfilter_backends = [CustomFilterBackend, SearchFilter]search_fields = ["status", "mode", 'risk']custom_query_fields = ["status", "mode", "risk"]


http://www.ppmy.cn/news/1533428.html

相关文章

Cell子刊被on hold,SCI 选刊投稿时该如何避开可能爆雷的期刊?

我是娜姐 迪娜学姐 ,一个SCI医学期刊编辑,探索用AI工具提效论文写作和发表。 Cell Press旗下的Heliyon,前两天刚被WOS宣布on hold预警了。 这本创刊于2015年的综合性OA期刊,发文范围广泛,包括生物、化学、物理、工程等…

【深度学习】深度学习框架有哪些及其优劣势介绍

本文摘要 在深度学习的开发中,有许多流行的深度学习框架可供使用。本文主要介绍其中一些常见的深度学习框架以及其优劣势。 注:个人观点,仅供学习参考。 原文地址:【深度学习】深度学习框架有哪些及其优劣势介绍 TensorFlow 开发…

WSL2 中配置桥接模式、虚拟交换机及固定 IP

WSL2 中配置桥接模式、虚拟交换机及固定 IP 一、创建虚拟交换机1.1 使用 Hyper-V 管理器创建虚拟交换机1.2 使用 PowerShell 创建虚拟交换机 二、更新 WSL 配置三、设置 WSL2 中的静态 IP、网关和 DNS3.1 编辑网络配置文件3.2 应用网络配置3.3 测试网络连接 四、重启 WSL 在使用…

鸿蒙开发(NEXT/API 12)【硬件(外设扩展驱动开发)】驱动开发服务

场景介绍 [DriverExtensionAbility]是Driver类型的ExtensionAbility组件,提供驱动相关扩展框架能力。对于部分设备,支持插入外接的硬件模块来扩展设备能力, 此时可以以应用方式安装该硬件模块的驱动程序。通过DriverExtensionAbility可实现此…

笔记整理—linux进程部分(5)syslog调试信息记录

守护进程将fd0、1、2指向垃圾桶,无法正常查看其进程信息或调试信息。 void openlog(const char *ident, int option, int facility);openlog("a.out",LOG_PID|LOG_CONS,LOG_USER); option是个宏操作操作选项,其中常用的为LOG_CONS将信息打印到…

UE5: Content browser工具编写02

DebugHeader.h 中的全局变量,已经在一个cpp file中被include了,如果在另一个cpp file中再include它,就会有一些conflicts。先全部给加一个static Add static keyword to debug functionsWrap all the functions inside of a namespaceprint …

【设计模式-命令】

定义 命令模式(Command Pattern)是一种行为设计模式,它将请求封装为一个对象,从而使您能够使用不同的请求、排队请求或记录请求,并支持可撤销的操作。该模式通过将请求与其执行分离,使得请求者和接收者之间…

【MAUI】CommunityToolkit社区工具包介绍

一、为什么需要声明式开发 .NET的MVVM,始于WPF,很古典,它甚至可能是现代前端框架“声明式开发”的鼻祖。声明式开发,之所以出现,是因为命令式开发在UI层和代码层上无法解耦的问题。如下图所示: 1、命令式开发:后台代码需要调用UI层的控件(label.Text),如果更新UI层…