gpt4 book ai didi

python - SQLAlchemy 一对多,子表没有主键

转载 作者:太空狗 更新时间:2023-10-29 22:09:51 24 4
gpt4 key购买 nike

是否可以在 SQLAlchemy 中创建没有主键的表?我要定义的关系如下:

class TPost(Base):
__tablename__ = "forum_post"
id = Column(Integer, primary_key = True)
topic_id = Column(Integer, ForeignKey("forum_topic.id"))
index = Column(Integer)
page = Column(Integer)
user_id = Column(Integer, ForeignKey("forum_user.id"))
posted_at = Column(DateTime)
post_text = Column(String)
has_quotes = Column(Boolean)
quotes = relationship("TQuote")

class TQuote(Base):
__tablename__ = "forum_quotes"
id = Column(Integer, ForeignKey("forum_post.id"))
is_direct = Column(Boolean)
quoted_text = Column(String)
quoted_id = Column(Integer)

如您所见,我实际上并不需要主键,而且我不打算在将来扩展 Quote 关系。

我的问题具体由以下错误消息表示:

sqlalchemy.exc.ArgumentError: Mapper Mapper|TQuote|forum_quotes 
could not assemble any primary key columns for mapped table 'forum_quotes'

编辑:(id,quoted_id) 对是唯一的,它代表大部分数据,但是当引用不是直接的(并且在这种情况下没有 quoted_id)时,我内联引用文本直接进入引用关系。我可以使用双表方法(其中间接引号有一个带主键的表),但我真的更愿意将其实现为单个一对多关系。我不想做的不仅仅是一个连接。

编辑 2:

我将对引号进行编号并使用外键 + 应用程序生成的数字作为 pkey,但仍然很烦人。现在来弄清楚语法。

编辑 3:

解决了编辑 2 中概述的问题。对 sql alchemy 非常恼火,因为它拥有实现关系所需的所有信息,即使在高级数据建模时也是如此。我明白了Sql Alchemy为什么要有主键的原因(让orm更容易实现)。

我开始质疑我为什么要使用 Sql Alchemy,没有它我可以使用 psycopg2 实现一种 UPSERT 或 CREATE_IF_NOT_EXIST 异步操作。 ORM 确实需要迎头 catch 。

最佳答案

我假设@TokenMacGuy 是正确的,您确实混淆了 PrimaryKeysurrogate key 的概念。在这种情况下,您的问题的答案是:

  • ,SA 不支持没有主键的表(以及与表的关系)
  • NO,您不需要为每个表创建代理键以用作主键。您可以使用具有唯一性的任意列组合来定义 PK。

例子见下面的代码:

class TPost(Base):
__tablename__ = 'forum_post'
id = Column(Integer, primary_key = True)
post_text = Column(String)
quotes = relationship("TQuote", backref="post")

class TQuote(Base):
__tablename__ = "forum_quotes"
id = Column(Integer, ForeignKey("forum_post.id"))
is_direct = Column(Boolean)
quoted_text = Column(String)
quoted_id = Column(Integer)
__table_args__ = (PrimaryKeyConstraint(id, quoted_id),)

关于python - SQLAlchemy 一对多,子表没有主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11232616/

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