2012-12-23 142 views
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() 
+44

+1爲有趣的標題 – Adam

回答

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')) 

我們不能因爲這是該Post.replies關係將添加到檢索Thread情況下使用的名稱thread

這是一個One to Many關係,如SQLAlchemy關係配置文檔中所述。

5

你應該在Post模型,上面寫着添加一個字段:

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

SQLAlchemy的應該是怎樣知道你是怎麼定義這種關係應該將thhread鏈接到帖子?這就是爲什麼你應該有一個外鍵從一個帖子到它的線程。你可以允許它爲空,如果它不屬於一個線程,它取決於你的用例。

+0

很好的答案,但我要把它交給martijn <3 –

+0

@JakobBowyer不用擔心! <3 :) – jadkik94

相關問題