尝试自我参考时出现错误

class Sku(Base, ReprDescrIdMixin):
    __tablename__ = 'SC84'
    id = Column("ID", String, primary_key=True)
    parent_code = Column("PARENTID",String, ForeignKey('sku.id'))
    parent = relationship('Sku', foreign_keys='Sku.parent_code')


sqlalchemy.exc.NoForeignKeysError: Could not determine join condition between parent/child tables on relationship Sku.parent - there are no foreign keys linking these tables.  Ensure that referencing columns are associated with a ForeignKey or ForeignKeyConstraint, or specify a 'primaryjoin' expression.


因此?这是工作http://docs.sqlalchemy.org/en/latest/orm/self_referential.html

最佳答案

尝试这个

class Sku(Base, ReprDescrIdMixin):
    __tablename__ = 'SC84'
    id = Column("ID", String, primary_key=True)
    parent_code = Column("PARENTID",String, ForeignKey(id))
    parent = relationship('Sku', foreign_keys=parent_code)


使用ForeignKey(...)时,您应该传递参考密钥,有两种方法可以执行此操作


通过传递表名和键与.相连的字符串,如ForeignKey("table_name.key")
通过传递ForeignKey(key)之类的Column对象


如果已经定义了key,则只能使用方法2,换句话说,如果ForeignKey(key)key = Column(...)之后

在我的示例中,我使用的是方法2,我更喜欢这种方式,以便由IDE分析代码。

看到这个link

关于python - 错误在哪里-邻接表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38841568/

10-11 18:22