烧瓶 - 塞拉尔奇米单表继承



sqlalchemy支持单表继承。

我的结构如下:

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效果很好。有什么想法解决问题?

我终于找到了一种提及应该如何工作的方式。我需要从初始mapper 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'
    }
    ...

最新更新