gpt4 book ai didi

python - 如何在 SQLAlchemy 的子类中定义基类中的表列和表名?

转载 作者:行者123 更新时间:2023-11-29 02:24:47 25 4
gpt4 key购买 nike

我需要有 2 个具有相同结构的独立表,这看起来像是继承方案,但我不希望基类与表相关联。 Base 仅用于定义子类中表的列。 The AbstractConcreteBase docs引导我以这种方式实现它:

status.py 中:

class Base(AbstractConcreteBase):
id = Column('id', Integer, primary_key=True)
date = Column('date', DateTime(), nullable=False)

class Status1(Base):
__tablename__ = 'status1'
__mapper_args__ = {
'polymorphic_identity': __tablename__,
'concrete': True
}

class Status2(Base):
__tablename__ = 'status2'
__mapper_args__ = {
'polymorphic_identity': __tablename__,
'concrete': True
}

part.py 中:

class Part(declarative_base()):
__tablename__ = 'parts'

id = Column('id', Integer, primary_key=True)
status1 = relationship('Status1', uselist=True, backref=backref('status1', order_by='Status1.date'))
status2 = relationship('Status2', uselist=True, backref=backref('status2', order_by='Status2.date'))

尝试此操作时,出现以下错误:

InvalidRequestError: When initializing mapper Mapper|Part|parts, expression 'Status1' failed to locate a name ("name 'Status1' is not defined"). If this is a class name, consider adding this relationship() to the <class 'package.Part'> class after both dependent classes have been defined.

建议?

最佳答案

您真正想要的是一个 Mixin 类。如果不想将基类与表相关联,则基类不应继承自 SQLAlchemy declarative_base。 mixin 将定义您想要的列/表结构。然后,您的子类继承mixin 和declarative_base

mixin 定义如下:

class StatusMixin(object):
id = Column('id', Integer, primary_key=True)
date = Column('date', DateTime(), nullable=False)

子类变得更加简单:

Base = declarative_base()

class Status1(StatusMixin, Base):
__tablename__ = 'status1'

class Status2(StatusMixin, Base):
__tablename__ = 'status2'

最后,您为 Part 类定义的 relationship 没有正确定义。要使用 backref,您需要在 status1status2 中定义一个将它们链接在一起的外键:

class Status1(StatusMixin, Base):
__tablename__ = 'status1'
part_id = Column('part_id', Integer, ForeignKey('parts.id'))

定义具有 backrefrelationship 的表需要有自己的表名作为 backref 而不是 的名称code>child1child2 表:

class Part(declarative_base()):
__tablename__ = 'parts'
id = Column('id', Integer, primary_key=True)
status1 = relationship('Status1', uselist=True, backref=__tablename__)
status2 = relationship('Status2', uselist=True, backref=__tablename__)

关于python - 如何在 SQLAlchemy 的子类中定义基类中的表列和表名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24535216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com