Flask-SQLAlchemy Single Table Inheritance

时光总嘲笑我的痴心妄想 提交于 2019-12-25 09:39:13

问题


SQLAlchemy support single table inheritance.

I have structure like:

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'
    }
    ...

When I try to run code, i get error like:

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.

When I add 'extend_existing' as table property:

__table_args__ = {'extend_existing': True}

Then I get next error when I try anything with model mentioned:

sqlalchemy.exc.NoForeignKeysError: Can't find any foreign key relationships between 'tbl_user' and 'tbl_user'.

This should be something straight forward, and should be solvable by single attribute, especially that it is working fine with SQLAlchemy. Any ideas how to solve problem?


回答1:


I've finally found a way how mentioned should work. I need to remove with_polymorfic option from initial mapper args and to add __tablename__ = None for children classes, so exact code look like:

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'
    }
    ...


来源:https://stackoverflow.com/questions/44782907/flask-sqlalchemy-single-table-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!