簡體   English   中英

Flask-SQLAlchemy單表繼承

[英]Flask-SQLAlchemy Single Table Inheritance

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一起正常工作。 任何想法如何解決問題?

我終於找到了一種提及方式。 我需要從初始映射器參數中刪除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'
    }
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM