繁体   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