簡體   English   中英

SQLAlchemy一對多,沒有子表具有主鍵

[英]SQLAlchemy one-to-many without the child table having a primary key

是否可以在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煉金術非常惱火,因為它具有實現關聯所需的所有信息,即使在高級別建模數據時也是如此。 我理解為什么Sql Alchemy想要擁有主鍵(使orm更容易實現)的原因。

我開始質疑為什么我使用Sql Alchemy,沒有它我可以使用psycopg2實現單向UPSERT或CREATE_IF_NOT_EXIST異步操作。 ORM真的需要追趕。

我假設@TokenMacGuy是對的,你真的混淆了PrimaryKeysurrogate key的概念。 在這種情況下,您的問題的答案是:

  • NO ,SA不支持沒有主鍵的表(因此與表的關系)
  • NO ,您不需要為每個表創建代理鍵以用primary key 您可以使用唯一的列的任意組合來定義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),)

添加一個額外的列以給引號一個索引,然后添加make這個新列的復合鍵+外鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM