sqlalchemy——@listens_for

  • 问:sqlalchemy如何实现:表中指定数据更新时,其time字段自动更新?
  • 答:使用listens_for 装饰器来注册事件监听器,确保在项目数据更新时触发相应的处理逻辑。

示例代码如下:

python 复制代码
# coding: utf-8
import datetime

from sqlalchemy.event import listens_for
from sqlalchemy.orm import declarative_base
from sqlalchemy import Column, String

Base = declarative_base()
'''
    项目表
'''

class ProjectTable(Base):
    __tablename__ = 'project'
    # 项目id
    id = Column(String(32), primary_key=True)
    # 项目名称
    name = Column(String(255))
    # 项目说明
    explain = Column(String(255))
    # 项目类型
    type = Column(String(20))
    # 更新时间
    time = Column(String(20), default=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    def __repr__(self):
        table = "project(id={}, name={}, explain={},time={},type={})"
        return table.format(self.id, self.name, self.explain, self.time, self.type)

    # 将查询结果转换为Json
    def to_json(self):
        _dict = self.__dict__
        if "_sa_instance_state" in _dict:
            del _dict["_sa_instance_state"]
        return _dict
# 添加监听,当数据更新时,自动更新time字段
@listens_for(ProjectTable, 'before_update')
def before_update_listener(mapper, connection, target):
    target.time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
相关推荐
小毛驴8502 小时前
Jupyter Notebook 安装步骤
ide·python·jupyter
BUG研究员_2 小时前
LangGraph节点缓存-CachePolicy
python·缓存·langraph
大模型丫丫2 小时前
LangGraph + MCP(Model Context Protocol)完整讲解
java·开发语言·数据库
凡泰AI2 小时前
小程序容器技术解析:一个能够同时在多端APP运行同一个小程序的SDK需要关注哪些内容?
开发语言·小程序·mpaas·uni·技术实践
小灰灰搞电子2 小时前
Rust+Slint 实现抽屉式侧边栏源码分享
开发语言·rust·侧边栏
quantdash_cc2 小时前
如何设计高效率的批量股票数据获取程序?QuantDash Python SDK 全市场行情拉取实战指南
开发语言·python·数据分析·量化交易·股票数据·quantdash
我不是程序员三三2 小时前
怎么监控电脑?企业办公终端监控建设实战与合规要点
服务器·数据库·电脑
这个DBA有点耶2 小时前
时间序列数据库选型2026:5款主流产品深度对比与场景适配
大数据·数据库·程序人生·架构·时序数据库·dba·数据库管理员
Jul1en_2 小时前
Matt 与 Uncle Bob 的播客访谈有感
开发语言·经验分享·笔记·ai·开源·github·ai编程
砚底藏山河2 小时前
拉数管道设计:从一次性脚本到可重启的数据流水线(魔码量化实战 #01)
java·数据库·python·金融·maven