两个sqlalchemy基类的包装器引发InvalidRequestError:多个映射的基数

时间:2019-07-03 09:37:34

标签: python sqlalchemy

我试图用几种方法来包装SQLAlchemy ORM类。如果仅在自定义类中包装一个类,则一切正常。但是有两个类,我会遇到错误

sqlalchemy.exc.InvalidRequestError: Class <class 'my_code.core.source.Source'> has multiple mapped bases: [<class 'my_code.core.source.SourceBase'>, <class 'my_code.core.source.SourceFieldBase'>

my_code/core/source.py中,

class SourceBase(Base):
    __tablename__ = 'cd_source'

    id = Column(Integer, primary_key=True)
    conn_id = Column(Integer, ForeignKey('cd_connection.id'))
    name = Column(String(100))
    tablename = Column(String(100))

class SourceFieldBase(Base):
    __tablename__ = 'cd_source_field'

    id = Column(Integer, primary_key=True)
    source_id = Column(Integer, ForeignKey('cd_source.id'))
    field = Column(String(100))
    type = Column(ENUM('integer', 'smallint', 'bigint', 'string', 'bool',
                       'array', 'document', 'float', 'numeric', 'datetime', 'date', name='field_type'))
    length = Column(Integer)
    association = Column(Integer, ForeignKey('cd_source_field.id'))
    filter_id = Column(Integer, ForeignKey('cd_filter.id'))
    op = Column(ENUM('ge', 'gt', 'lt', 'le', 'eq', 'ne',
                     'not', 'is', name='operation_type'))

现在,我创建一个使用这两个类的包装器。实际上,add_source方法将数据添加到cd_source表和cd_source_field表中。我不确定该怎么做,因为SQLAlchemy文档使我感到困惑。

class Source(SourceBase, SourceFieldBase):
    def __init__(self):
        self.engine = create_engine(SQLALCHEMY_CONN)
        self.Session = sessionmaker(bind=self.engine)

    def add_source(self, name, conn_id, tablename, field_list):
        session = self.Session()
        try:
            source = SourceBase(name=name, conn_id=conn_id, tablename=tablename)
            session.add(source)
            source_id = source.id
            for field in field_list:
                source_field = SourceFieldBase(source_id=source_id, **field)
                session.add(source_field)
            session.commit()
            return source.id
        except Exception as e:
            # TODO: Handle the exception by raising a custom Exception
            traceback.print_exc()
        finally:
            if session.dirty:
                session.commit()

我是sqlalchemy ORM的新手,我正在尝试将其作为实验项目以更好地学习它。如果这是新手问题,请告诉我。我浏览了文档,但无法弄清楚该引用哪一部分。

我在Google上搜索时发现的一些链接,但一字听不懂: https://github.com/sqlalchemy/sqlalchemy/issues/4699 https://github.com/sqlalchemy/sqlalchemy/issues/4321

0 个答案:

没有答案