14

我使用 sqlalchemy 来设计一个论坛风格的网站。我开始敲掉这个设计,但每次我尝试用一​​些插件测试它时,它都会倾倒一块砖;

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

这是我的“模型”

from sqlalchemy import Integer, Column, String, create_engine, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker, backref
from .database import Base # declarative base instance

class User(Base):
    __tablename__ = "user"
    id = Column(Integer, primary_key=True)
    username = Column(String, unique=True)
    email = Column(String, unique=True)
    threads = relationship("Thread", backref="user")
    posts = relationship("Post", backref="user")

class Post(Base):
    __tablename__ = "post"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    body = Column(String)
    author = Column(Integer, ForeignKey("user.id"))


class Thread(Base):
    __tablename__ = "thread"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    desc = Column(String)
    replies = relationship("Post", backref="thread")
    author_id = Column(Integer, ForeignKey("user.id"))
    board_id = Column(Integer, ForeignKey("board.id"))

class Board(Base):
    __tablename__ = "board"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    desc = Column(String)
    threads = relationship("Thread", backref="board")
    category_id = Column(Integer, ForeignKey("category.id"))

class Category(Base):
    __tablename__ = "category"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    desc = Column(String)
    threads = relationship("Board", backref="category")


engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
session_factory = sessionmaker(bind=engine)
session = session_factory()
4

2 回答 2

5

您应该在 Post 模型中添加一个字段,内容为:

thread_id = Column(Integer, ForeignKey("thread.id"), nullable=True, default=None)

SQLAlchemy 应该如何知道您定义的这种关系应该如何将线程链接到帖子?这就是为什么你应该有一个从帖子到它的线程的外键。您可以允许它为空,如果它不属于线程,则取决于您的用例。

于 2012-12-23T10:55:32.260 回答
5

您的Post模型没有thread参考。添加一列以Post引用Thread帖子所属的:

class Post(Base):
    __tablename__ = "post"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    body = Column(String)
    author = Column(Integer, ForeignKey("user.id"))
    thread_id = Column(Integer, ForeignKey('thread.id'))

我们不能使用该名称thread,因为这是Post.replies关系将添加到检索到的Thread实例的名称。

这是SQLAlchemy 关系配置文档中记录的一对多关系。

于 2012-12-23T11:09:32.197 回答