我发现,如果__table_args__
出现在单表继承设置中的子类上,SQLAlchemy抛出sqlalchemy.exc.ArgumentError: Can't place __table_args__ on an inherited class with no table
。同时,可以在子类上定义一个带有index=True
的列,这将以与__table_args__
相同的方式修改父表。在
以下是我的设置:
import sqlalchemy as sa
import sqlalchemy.ext.declarative
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = sa.Column(sa.Integer, primary_key=True)
type = sa.Column(sa.Text, nullable=False)
__mapper_args__ = {
'polymorphic_on': type,
}
class B(A):
b = sa.Column(sa.Integer, index=True)
__mapper_args__ = {
'polymorphic_identity': 'b',
}
class C(A):
c = sa.Column(sa.Integer)
__mapper_args__ = {
'polymorphic_identity': 'c',
}
__table_args__ = (
sa.Index('ix_test', c),
)
engine = sa.engine.create_engine("sqlite://", echo=True)
Base.metadata.create_all(engine)
session = sa.orm.Session(engine)
session.add_all([
B()
])
session.commit()
print(session.query(A))
它抛出:
^{pr2}$有人知道什么变通办法吗?在
索引可以放在表定义之外。在
在更新到SQLAlchemy 2.3之后,我开始遇到这个错误。在
如果您可以删除表参数,它将起作用(但可能会抱怨其他事情,特别是当两个子类共享一个字段名时—这是我使用
__table_args__ = {'extend_existing': True}
时发生的。在最后,解决方法是显式地在子类上指定表名,例如:
一个粗略的例子,但希望这个想法是有意义的-餐厅和酒吧都有一个字段来保存他们的酒精许可证信息,所以我们希望这两个使用表中现有的字段,而不是冲突-现在我们必须从SQLAlchemy 2.3开始指定表名。在
我知道这个例子和问题(关于索引)不是完全相同的问题,但是它导致了同样的错误,这个解决方案在这种情况下应该也能起作用。在
相关问题 更多 >
编程相关推荐