gpt4 book ai didi

python - Flask-SQLAlchemy 单表继承

转载 作者:行者123 更新时间:2023-12-05 04:10:14 31 4
gpt4 key购买 nike

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 一起正常工作。有解决问题的想法吗?

最佳答案

我终于找到了一种应该如何工作的方法。我需要从初始映射器参数中删除 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'
}
...

关于python - Flask-SQLAlchemy 单表继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44782907/

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