gpt4 book ai didi

python - NoForeignKeysError : Could not determine join condition . ..没有链接这些表的外键

转载 作者:太空狗 更新时间:2023-10-29 17:19:32 26 4
gpt4 key购买 nike

我正在使用 sqlalchemy 设计一个论坛风格的网站。我开始敲定设计,但每次我尝试用一​​些插入物对其进行测试时,它都会倾倒一 block 砖;

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

最佳答案

您的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 关系配置文档中记录的关系。

关于python - NoForeignKeysError : Could not determine join condition . ..没有链接这些表的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14010347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com