【问题标题】:not case-sensitive column names in SQLAlchemy?SQLAlchemy 中的列名不区分大小写?
【发布时间】:2014-03-26 19:03:03
【问题描述】:

我正在反映我的 MySQL 数据库的一些表,并且我想对它们的一些列应用过滤器。

meta = MetaData(bind=engine)
table_backlog= meta.tables['backlog']
all_filters = and_(and_(*all_filters),and_(table_backlog.c.month != "NULL",table_backlog.c.month != None))

但问题是有时列名从month 更改为Month,因此我的程序不再工作。 (我无法控制数据库,它由其他人管理)。

那么有没有办法让 SQLAlchemy/Python 中的列不区分大小写?

【问题讨论】:

  • 列名具体在哪里以及为什么会更改?您可以在Column 构造函数中显式命名列,这样它们就不会依赖于您如何命名表/模型类中的属性。

标签: python mysql sqlalchemy


【解决方案1】:

可能有更好的方法,但一种简单的方法是只获取一个忽略大小写的列:

meta = MetaData(bind=engine)
table_backlog= meta.tables['backlog']

cols = [_c for _c in table_backlog.columns if _c.name.lower() == "month"]
assert (cols and len(cols) == 1), 'None or multiple column(s) named "month" found'
col_month = cols[0]

all_filters = and_(and_(*all_filters),and_(month_col != "NULL", month_col != None))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 2017-12-08
    • 2014-09-06
    • 2014-03-18
    • 2022-01-07
    • 2023-04-10
    • 2012-02-03
    相关资源
    最近更新 更多