SQLAlchemy中的多态自引用表

0 投票
1 回答
797 浏览
提问于 2025-04-17 03:23

我现在在我的模型上遇到了一些问题。我发现了这两个问题(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

我哪里做错了?谢谢。

1 个回答

3

id这个名字用在列上其实不太好,因为id是一个内置的函数,所以它总是会被定义。如果你给主键起个不那么常见的名字,你就会看到不同的错误信息,那样就会更明显了。

class Comment(Post):
    __tablename__ = 'comment'
    __mapper_args__ = {'polymorphic_identity': 'comment', 'inherit_condition': (id == Post.id)}
#                                                                               ^^

这里的id指的是__builtins__.id,这是一个返回Python对象地址的函数。可能这并不是你想要的结果。

简单的解决办法是,把__mapper_args__放到你把id别名为实际表列的那一行下面。

撰写回答