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")
相关推荐
就不掉头发几秒前
如何优化程序的性能
开发语言
手写码匠7 分钟前
MCP协议从零实现:手写一个完整的 Model Context Protocol 服务器与客户端
开发语言·数据结构
数行拙笔8 分钟前
Redis---zset类型
数据库·redis·缓存
老大白菜9 分钟前
Omnigent(omni)使用说明
服务器·数据库·microsoft
夜瞬15 分钟前
内生可解释性:从黑盒深度模型到可理解、可干预的智能系统
人工智能·python
良木生香27 分钟前
【C++初阶】STL—— Stack & Queue 从入门到精通:容器适配器、迭代器与经典面试题
java·开发语言·c++·算法·zookeeper
lbb 小魔仙35 分钟前
Python 性能分析工具实战:cProfile、memory_profiler、line_profiler 使用指南
开发语言·python
数智化管理手记38 分钟前
全面预算管理执行偏差大?全面预算管理全流程落地步骤是什么
大数据·网络·数据库·人工智能·数据挖掘
小小晓.39 分钟前
C++小白记:vector
开发语言·c++·算法
小刘学技术1 小时前
AI人工智能决策树分类器:原理、实现与应用
开发语言·人工智能·python·算法·决策树·机器学习·数据挖掘