sqlalchemy - 在 SQL Alchemy (1.0.4) 中获取表列

标签 sqlalchemy

我已经意识到,在 的最新版本中SQLAlchemy (v1.0.4) 使用 时出现错误table.c.keys() 用于选择列。

from sqlalchemy import MetaData
from sqlalchemy import (Column, Integer, Table, String, PrimaryKeyConstraint)

metadata = MetaData()

table = Table('test', metadata,
        Column('id', Integer,nullable=False),
        Column('name', String(20)),
        PrimaryKeyConstraint('id')
    )

stmt = select(table.c.keys()).select_from(table).where(table.c.id == 1)

在以前的版本中,它曾经可以正常工作,但现在会引发以下错误:
sqlalchemy/sql/elements.py:3851: SAWarning: Textual column expression 'id' should be explicitly declared with text('id'), or use column('id') for more specificity.
sqlalchemy/sql/elements.py:3851: SAWarning: Textual column expression 'name' should be explicitly declared with text('name'), or use column('name') for more specificity.

是否有用于检索所有这些表列的函数,而不是使用如下所示的列表理解? [text(x) for x in table.c.keys()]

最佳答案

不,但你总是可以推出自己的。

def all_columns(model_or_table, wrap=text):
    table = getattr(model_or_table, '__table__', model_or_table)
    return [wrap(col) for col in table.c.keys()]

那么你会像这样使用它
stmt = select(all_columns(table)).where(table.c.id == 1)

或者
stmt = select(all_columns(Model)).where(Model.id == 1)

请注意,在大多数情况下,您不需要 select_from ,即当您实际上没有加入其他表时。

关于sqlalchemy - 在 SQL Alchemy (1.0.4) 中获取表列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30238998/

相关文章:

Python Flask、SQLAlchemy 关系

python - SQLAlchemy : object. id 在括号中返回为 int,而不是 int

python - SQLAlchemy 正则表达式与 MySQL 数据库使用\b

SQLAlchemy 引发完整性错误, "update or delete on table violates foreign key constraint"

python - SQLAlchemy 子字符串在字符串中

python - SQLAlchemy:避免延迟加载的浅拷贝

python - 让 SQLAlchemy 在连接中使用所需的表

python - 删除 sqlalchemy 中多对多辅助表关联中的所有内容

sqlalchemy - 使用 Flask-SQLAlchemy 自动映射多个数据库

python - 如何部署 Python/SQLAlchemy 应用程序?