覆盖 sqlalchemy 反射表中的默认值 [英] Override default in sqlalchemy reflected tables

查看:28
本文介绍了覆盖 sqlalchemy 反射表中的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在现有的 mysql 数据库中反映了大量表.我想表示任何表中某个名称的任何列默认为 datetime.now().然而,天真地循环遍历表和列,只是在我发现具有特定名称的那些表和列上设置默认值不起作用,在执行 session.add(); 时;session.flush() 我收到以下错误:

I've reflecting a load of tables in an exiting mysql db. I want to express that any columns of a certain name in any table default to datetime.now(). However naively looping through the tables and columns and just setting default on those I find that have a certain name doesn't work, When doing session.add(); session.flush() I get the following error:

AttributeError: 'builtin_function_or_method' object has no attribute '__visit_name__'

这似乎与对 _set_parent 的调用有关(以及 sqlalchemy.schema 中第 721 行的 this self._init_items(*toinit).

This would seem to be tied up in the call to _set_parent (and the this self._init_items(*toinit) at line 721 in sqlalchemy.schema.

有谁知道是否有一种方法可以做到这一点,而无需遍历我所有的反射表并在每个地方都添加 Column(..) 行,这些行都在做同样的事情或诉诸非常丑陋的 hacks?

Does anyone know if there's a way to do this without either going through all of my reflected tables and adding Column(..) lines every where all doing the same thing or resorting to really ugly hacks?

推荐答案

五年后,您可以使用事件监听器[1].您可以使用要运行的函数注册侦听器:

Five years later, you can use event listeners[1]. You can register a listener with a function to run:

def do_this_on_column_reflect(inspector, table, column_info):
    column_name = column_info.get("name")
    if column_name == "create_datetime":
        column_info["default"] = datetime.now()
event.listen(Table, "column_reflect", do_this_on_column_reflect)

[1] http://docs.sqlalchemy.org/en/latest/core/events.html#sqlalchemy.events.DDLEvents.column_reflect[2] http://docs.sqlalchemy.org/en/latest/core/event.html#sqlalchemy.event.listen

这篇关于覆盖 sqlalchemy 反射表中的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆