SQLAlchemy:将表映射到类

2024-09-28 23:19:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用例,我希望能够使用declaritiveapi部分地定义一个表,然后添加一些列属性,这些属性与定义表类后自动生成的主键相对应。你知道吗

例如,假设我将此表作为起点:

Base = declarative_base(cls=DeferredReflection)

class my_table(Base):
    __tablename__ = "my_table"
    __table_args__ = {'schema': 'my_schema'}

    @hybrid_property
    def my_attr(self):
        return func.coalesce(self.attr_1, self.attr_2, self.attr_3)

该表没有主键,但它有一个实际上是主键的主索引。默认情况下,SQLAlchemy不使用主索引作为主键。所以我要做的是尝试从表中已有的主索引构建主键。你知道吗

这是我写的一节课:

class AddPrimaryKeys():
    '''
    This class provides a function that will automatically add primary key
    definitions using the established primary index.
    '''
    def __init__(self, inspector):
        self.inspector = inspector

    def __call__(self, table, metadata):
        pkey_cols = self.__build_pkey_from_index(table)
        return self.__add_primary_keys(table, pkey_cols, metadata)

    def __build_pkey_from_index(self, table):
        tablename = table.__tablename__
        schema = table.__table_args__['schema']
        indices = self.inspector.get_indexes(tablename, schema=schema)
        pkey_info = self.__get_column_info(tablename, schema, indices)
        pkey_cols = self.__build_columns(pkey_info, table)
        return pkey_cols

    def __get_column_info(self, tablename, schema, indices):
        columns = self.inspector.get_columns(tablename, schema=schema)
        index_names = indices[0]['column_names']
        pkey_info = []
        for c in columns:
            if c['name'] in index_names:
                pkey_info.append((c['name'], c['type']))
        return pkey_info

    def __build_columns(self, pkey_info, table):
        pkey_cols = []
        for key_name, key_type in pkey_info:
            column = Column(key_name, key_type, primary_key=True)
            pkey_cols.append(column)
        print(pkey_cols)
        return pkey_cols

    def __add_primary_keys(self, table, pkey_cols, metadata):
        tablename = table.__tablename__
        schema = table.__table_args__['schema']
        table_map = Table(name=tablename, metadata=metadata, schema=schema, *pkey_cols)
        # properties={'primary_key':pkey_cols}
        # mapper(table, table_map, properties=properties)
        mapper(table, table_map)
        return metadata

我这样称呼这个班:

insp = inspect(td_engine)
from lib.pkey_lookup import AddPrimaryKeys
add_pkeys = AddPrimaryKeys(insp)
add_pkeys(my_table, Base.metadata)

以下是列列表的外观:

[Column('some_attr', DECIMAL(precision=18), table=None, primary_key=True, nullable=False), Column('another_attr', DECIMAL(precision=18), table=None, primary_key=True, nullable=False)]

这将引发以下错误:

AttributeError: Neither 'Column' object nor 'Comparator' object has an attribute 'tables'

您还可以看到,我只是尝试将主键列声明为properties dict的一部分,在这种情况下,我将放弃整个__build_columns方法。你知道吗

有人对如何解决这个错误有什么建议吗?也许这是一种更好的方法,可以将从insp.get_indexes()中标识的列指定为表上的主键?你知道吗

EDIT:还应该添加这样一点:在本文末尾,我想调用Base.prepare(engine)来填充数据库中的rest或table属性。你知道吗


Tags: columnskeyselfinforeturnschemadeftable