如何在列名(和表名)中有空格的数据库上使用 sqlalchemy?
db.auth_stuff.filter("db.auth_stuff.first name"=='Joe')
显然不行。我不想在进行反射时手动定义所有内容,而是想在从数据库读取的现有表名之间放置类似 lambda x: x.replace(' ','_')
的东西,并在我的模特。 (创建一个通用函数来重命名所有不能很好地与 python 一起工作的表名-保留字等也可能很有用)
有没有一种简单/干净的方法可以做到这一点?
我认为我需要定义自己的映射器类?
https://groups.google.com/forum/#!msg/sqlalchemy/pE1ZfBlq56w/ErPcn1YYSJgJ
或者使用某种 __mapper_args__
参数 -
http://docs.sqlalchemy.org/en/rel_0_8/orm/mapper_config.html#naming-all-columns-with-a-prefix
理想情况下:
class NewBase(Base):
__mapper_args__ = {
'column_rename_function' : lambda x: x.replace(' ','_')
}
class User(NewBase):
__table__ = "user table"
}
最佳答案
您可以使用 reflection event 来做到这一点给列一个 .key,但是当涉及主键列时,完整的配方有一个错误,该错误在尚未发布的 0.8.3 版本(以及主版本)中得到修复。如果您在 https://bitbucket.org/zzzeek/sqlalchemy/get/rel_0_8.zip 查看 0.8.3这个食谱甚至可以使用主键列:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
Base = declarative_base(cls=DeferredReflection)
e = create_engine("sqlite://", echo=True)
e.execute("""
create table "user table" (
"id col" integer primary key,
"data col" varchar(30)
)
""")
from sqlalchemy import event
@event.listens_for(Table, "column_reflect")
def reflect_col(inspector, table, column_info):
column_info['key'] = column_info['name'].replace(' ', '_')
class User(Base):
__tablename__ = "user table"
Base.prepare(e)
s = Session(e)
print s.query(User).filter(User.data_col == "some data")
DeferredReflection是与声明式 + 反射一起使用的可选助手。
关于python - sqlalchemy - 反射(reflect)带空格的表和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19215759/