SQLAlchemy一对多,没有子表具有主键

Has*_*yed 6 python database orm ddl sqlalchemy

是否可以在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)   
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我并不需要主键,我不打算Quote将来扩展这种关系.

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

sqlalchemy.exc.ArgumentError: Mapper Mapper|TQuote|forum_quotes 
could not assemble any primary key columns for mapped table 'forum_quotes'
Run Code Online (Sandbox Code Playgroud)

编辑:(id,quoted_id)对是唯一的,它存在于大多数数据中,但是当引用不是直接的(并且在这种情况下没有quoted_id)时,我将引用的文本直接内联到引用关系中.我可以使用双表方法(其中直接引号具有带主键的表),但我真的宁愿将其实现为单个一对多关系.我不想做一次以上的加入.

编辑2:

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

编辑3:

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

我开始质疑为什么我使用Sql Alchemy,没有它我可以使用psycopg2实现单向UPSERT或CREATE_IF_NOT_EXIST异步操作.ORM真的需要追赶.

van*_*van 13

我假设@TokenMacGuy是对的,你真的很混淆PrimaryKey和a 的概念surrogate key.在这种情况下,您的问题的答案是:

  • NO,SA不支持没有主键的表(因此与表的关系)
  • NO,您不需要为每个表创建一个代理键,以便充当a 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),)
Run Code Online (Sandbox Code Playgroud)


Has*_*yed 1

添加一个附加列来为引号提供索引,然后添加该新列 + 外键的复合键。