SQLAlchemyで具象テーブルの継承を使用しています。宣言的スタイルのモデルクラスでは、私はそれをうまく設定しました。シェルでそれをテストしながら、それが正常に動作しますSQLAlchemyポリモーフィックコンクリート継承との関係
class Entry(AbstractConcreteBase, db.Model):
"""Base Class of Entry."""
id = db.Column(db.Integer, primary_key=True, nullable=False)
created = db.Column(db.DateTime, nullable=False)
post_id = declared_attr(lambda c: db.Column(db.ForeignKey("post.id")))
post = declared_attr(lambda c: db.relationship("Post", lazy="joined"))
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()
@declared_attr
def __mapper_args__(cls):
# configurate subclasses about concrete table inheritance
return {'polymorphic_identity': cls.__name__,
'concrete': True} if cls.__name__ != "Entry" else {}
class TextEntry(Entry):
"""Text and Article Entry."""
text = db.deferred(db.Column(db.Text, nullable=False))
class PhotoEntry(Entry):
"""Photo Entry."""
path = db.deferred(db.Column(db.String(256), nullable=False))
:だけのよう
私のコード他のモデルで関係を設定しながら
>>> from models.entry import Entry
>>>
>>> Entry.query.all()
[<PhotoEntry 'Title' created by tonyseek>,
<PhotoEntry 'TITLE 2' created by tonyseek>,
<PhotoEntry 'Title 3' created by tonyseek>,
<PhotoEntry 'Title 4' created by tonyseek>,
<TextEntry 'Title' created by tonyseek>]
は、その後、私はトラブルに陥ります。各エントリには、という外部キーがあり、Post
モデルに参加しましたが、Post
にはバックリファレンスを定義できませんでした。それが動作しないことができます。
class Post(db.Model):
"""An Post."""
id = db.Column(db.Integer, primary_key=True, nullable=False)
description = db.Column(db.Unicode(140), nullable=False)
entries = db.relationship(Entry, lazy="dynamic")
それは例外を上げ、言った:
InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Class 'models.entry.Entry' is not mapped.
明白なEntry
は本物が存在テーブルにマップできませんでした抽象クラスです。公式サイトの文書には例がありますが、基本クラスは抽象ではありません。では、抽象モデルと多相関係を設定するにはどうしたらよいですか?