SQLAlchemy支持single table inheritance。
我的结构如下:
class User(db.Model):
__tablename__ = 'tbl_user'
type = db.Column(db.String(32))
...
__mapper_args__ = {
'polymorphic_identity': 'user',
'polymorphic_on': type,
'with_polymorphic': '*'
}
class Tourist(User):
__mapper_args__ = {
'polymorphic_identity': 'tourist'
}
...
class Guide(User):
__mapper_args__ = {
'polymorphic_identity': 'guide'
}
...
当我尝试运行代码时,我收到如下错误:
sqlalchemy.exc.InvalidRequestError: Table 'tbl_user' is already defined for this MetaData instance. Specify 'extend_existing=True' to redefine options and columns on an existing Table object.
当我将'extend_existing'添加为表属性时:
__table_args__ = {'extend_existing': True}
当我尝试使用所提到的模型时,我会收到下一个错误:
sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'tbl_user' and 'tbl_user'.
这应该是直截了当的,并且应该可以通过单个属性来解决,特别是它可以与SQLAlchemy一起使用。 任何想法如何解决问题?
答案 0 :(得分:0)
我终于找到了提到应该如何运作的方式。我需要从初始映射器args中删除with_polymorfic
选项,并为子类添加__tablename__ = None
,所以确切的代码如下所示:
class User(db.Model):
__tablename__ = 'tbl_user'
type = db.Column(db.String(32))
...
__mapper_args__ = {
'polymorphic_identity': 'user',
'polymorphic_on': type,
} # remove with_polymorphic
class Tourist(User):
__tablename__ = None # Add table name to be None
__mapper_args__ = {
'polymorphic_identity': 'tourist'
}
...
class Guide(User):
__tablename__ = None # Add table name to be None
__mapper_args__ = {
'polymorphic_identity': 'guide'
}
...