[英]Self-referential tables with polymorphism in SQLAlchemy
所以我現在模型有問題。 我遇到了這兩個( 1 )( 2 )問題,這些問題對我有很大幫助,但現在我陷入了困境。 這是我當前的代碼:
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
type = Column('type', String(10))
created = Column(TIMESTAMP(), default=datetime.now())
updated = Column(TIMESTAMP(), default=datetime.now())
poster_id = Column(Integer, ForeignKey('person.id'))
poster = relationship('Person', backref=backref('posts'))
__mapper_args__ = {'polymorphic_on': type}
class Comment(Post):
__tablename__ = 'comment'
__mapper_args__ = {'polymorphic_identity': 'comment', 'inherit_condition': (id == Post.id)}
id = Column(Integer, ForeignKey('post.id'), primary_key=True)
post_id = Column(Integer, ForeignKey('post.id'))
post = relationship('Post', primaryjoin=('Comment.post_id == Post.id'), backref=backref('comments'), remote_side='Post.id')
text = Column(Text)
我得到的當前錯誤是:
TypeError: Incompatible collection type: int is not list-like
我究竟做錯了什么? 謝謝。
id
是列的真正不幸的名字; id
是一個內置函數,因此它總是被定義。 如果您為主鍵選擇了一個不太主流的名稱,那么您將看到一個不同的錯誤,這很明顯。
class Comment(Post):
__tablename__ = 'comment'
__mapper_args__ = {'polymorphic_identity': 'comment', 'inherit_condition': (id == Post.id)}
# ^^
該id
指向__builtins__.id
,這是一個返回python對象地址的函數。 可能不是您的意思。
簡單的解決方案:將__mapper_args__
移動到別名id
所在的行下方,以表示實際的表Column。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.