Flask-SQLAlchemy 单表继承

3

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时可以正常工作。有什么解决问题的想法吗?
1个回答

3

我最终找到了如何让提到的功能正常工作的方法。 我需要从初始映射器参数中删除 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'
    }
    ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接