我怎样才能获得Model列的列表(以及后面的id列和关系):
columns = Model.cols_list
这样列表就可以构建一次,并在需要时重复使用。
我会写这样的东西,我无法开始工作:
from sqlalchemy.orm import class_mapper
class Model(DeclarativeBase):
__tablename__ = 'model_table'
id = Column(Integer, primary_key=True, autoincrement=True)
col1 = Column(...)
col2 = Column(...)
...
cols_list = None
@classmethod
def cols_list(cls):
if cls.cols_list is None:
cls.cols_list = [key.name for key in class_mapper(cls).primary_key]
return cls.cols_list
答案 0 :(得分:1)
class Model(DeclarativeBase):
__tablename__ = 'model_table'
id = Column(Integer, primary_key=True, autoincrement=True)
col1 = Column(...)
col2 = Column(...)
@classmethod
def col_list(cls):
mapper = inspect(cls)
return mapper.columns
@classmethod
def relationships(cls):
mapper = inspect(cls)
return mapper.relationships
http://docs.sqlalchemy.org/en/rel_0_9/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.columns
http://docs.sqlalchemy.org/en/rel_0_9/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.attrs
等