使用SQLAlchemy
,我希望继承一个包含多个主键的模型,例如:
from sqlalchemy import (Column, Integer, create_engine, ForeignKey,
ForeignKeyConstraint, UniqueConstraint)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.declarative import declared_attr
#engine = create_engine('sqlite:///memory')
engine = create_engine('postgres:///memory')
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
id2 = Column(Integer, primary_key=True)
class Test2(Test):
__tablename__ = 'test2'
id = Column(Integer, ForeignKey('test.id'), primary_key=True)
id2 = Column(Integer, ForeignKey('test.id2'), primary_key=True)
@declared_attr
def __table_args__(cls):
return (
UniqueConstraint(cls.id, cls.id2),
ForeignKeyConstraint([cls.id, cls.id2],
[Test.id, Test.id2]),
)
@declared_attr
def __mapper_args__(cls):
return {
'inherit_condition': (cls.id == Test.id and cls.id2 == Test.id2),
}
Base.metadata.create_all(engine)
继承仅使用一个主键列,这不是我的用例。我有两个String主键列,我使用SQLAlchemy
的多态模式。我没有编写所有代码,无论是否有多态配置,问题都是一样的。
此代码适用于sqlite
,但不适用于postgres
,__table_args__
在这里没用,我想念什么?
问候
答案 0 :(得分:0)
我发现,必须删除column
中的外键约束
from sqlalchemy import (Column, Integer, create_engine,
ForeignKeyConstraint)
from sqlalchemy.ext.declarative import declarative_base
#engine = create_engine('sqlite:///memory')
engine = create_engine('postgres:///memory')
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
id2 = Column(Integer, primary_key=True)
class Test2(Test):
__tablename__ = 'test2'
# No foreign key here
id = Column(Integer, primary_key=True)
id2 = Column(Integer, primary_key=True)
__table_args__ = (
# this constraints must be the alone to Test model
ForeignKeyConstraint([id, id2], [Test.id, Test.id2]),
)
Base.metadata.create_all(engine)