任何人都可以告诉我的关系有什么不对吗?

时间:2012-12-23 10:49:44

标签: python orm sqlalchemy

我使用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()

2 个答案:

答案 0 :(得分:5)

您应该在Post模型中添加一个字段:

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

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

答案 1 :(得分: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个实例。

这是一个One to Many关系,如SQLAlchemy Relationship Configuration文档中所述。