gpt4 book ai didi

python - 无法在单表继承设置中的子类上定义 __table_args__

转载 作者:行者123 更新时间:2023-11-28 22:28:00 31 4
gpt4 key购买 nike

我发现如果 __table_args__ 存在于单表继承设置中的子类中,SQLAlchemy 会抛出 sqlalchemy.exc.ArgumentError: Can't place __table_args__ on an inherited没有表的类。同时,可以在子类上定义一个带有 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))

它抛出:

Traceback (most recent call last):
File "test.py", line 29, in <module>
class C(A):
File "/home/andrei/projects/my_project/.tox/dev/lib/python3.5/site-packages/sqlalchemy/ext/decla
rative/api.py", line 64, in __init__
_as_declarative(cls, classname, cls.__dict__)
File "/home/andrei/projects/my_project/.tox/dev/lib/python3.5/site-packages/sqlalchemy/ext/decla
rative/base.py", line 88, in _as_declarative
_MapperConfig.setup_mapping(cls, classname, dict_)
File "/home/andrei/projects/my_project/.tox/dev/lib/python3.5/site-packages/sqlalchemy/ext/decla
rative/base.py", line 103, in setup_mapping
cfg_cls(cls_, classname, dict_)
File "/home/andrei/projects/my_project/.tox/dev/lib/python3.5/site-packages/sqlalchemy/ext/decla
rative/base.py", line 133, in __init__
self._setup_inheritance()
File "/home/andrei/projects/my_project/.tox/dev/lib/python3.5/site-packages/sqlalchemy/ext/decla
rative/base.py", line 442, in _setup_inheritance
"Can't place __table_args__ on an inherited class "
sqlalchemy.exc.ArgumentError: Can't place __table_args__ on an inherited class with no table.

有人知道任何解决方法吗?

最佳答案

索引可以放在表定义之外。

class C(A):
c = sa.Column(sa.Integer)

__mapper_args__ = {
'polymorphic_identity': 'c',
}

Index('ix_test', C.c)

关于python - 无法在单表继承设置中的子类上定义 __table_args__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43832848/

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