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")
相关推荐
FriendshipT几秒前
Ultralytics:解读C3Ghost模块
人工智能·pytorch·python·深度学习·目标检测
Java面试题总结5 分钟前
Vue3流式调用大模型接口完整实践
后端·python
LaughingZhu8 分钟前
Product Hunt 每日热榜 | 2026-07-17
前端·数据库·人工智能·经验分享·mysql·chatgpt·html
怪兽学LLM9 分钟前
AI Agent 记忆系统设计:长短期记忆如何实现?什么时候存?什么时候查?
人工智能·python
DFT计算杂谈11 分钟前
DeepSeek 集群服务器无root本地部署指南
数据库·人工智能·python·opencv·算法
潇凝子潇13 分钟前
UnsupportedOperationException
java·前端·数据库
卷无止境14 分钟前
Python 跨平台 GUI 解决方案全景报告
前端·python
七夜zippoe19 分钟前
DolphinDB实时聚合计算:多维度聚合
数据库·dolphindb
码农学院22 分钟前
电子产品企业泉州网络推广如何精准触达目标采购商
开发语言·php
qq_33776320191 小时前
国际期货资管系统开发方案|内外盘交易平台源码授权与二次开发支持
java·c语言·开发语言·c++·c#