将已处理的类属性添加到映射以从class_mapper内省获取Model的列列表

时间:2014-02-04 17:01:08

标签: python sqlalchemy

我怎样才能获得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

1 个答案:

答案 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.column_attrs

http://docs.sqlalchemy.org/en/rel_0_9/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.relationships

http://docs.sqlalchemy.org/en/rel_0_9/orm/mapper_config.html#sqlalchemy.orm.mapper.Mapper.attrs