sqlalchemy - reflecting tables and columns with spaces

白昼怎懂夜的黑 提交于 2019-11-28 14:00:39

you can do this using a reflection event to give the columns a .key, however the full recipe has a bug when primary key columns are involved, which was fixed in the still-unreleased 0.8.3 version (as well as master). If you check out 0.8.3 at https://bitbucket.org/zzzeek/sqlalchemy/get/rel_0_8.zip this recipe will work even with primary key cols:

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 is an optional helper to use with declarative + reflection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!