简体   繁体   English

如何使用 SQLAlchemy 插入复合主键?

[英]How to insert composite primary key using SQLAlchemy?

When I try to insert the composite primary key connection returns 0 rows:当我尝试插入复合主键连接时返回 0 行:

CompetitionRound = sa.Table('CompetitionRound', metadata,
                            sa.Column('CompetitionId', sa.Integer, sa.ForeignKey('Competitions.Id'), primary_key=True),
                            sa.Column('RoundId', sa.Integer, sa.ForeignKey('Rounds.Id'), primary_key=True))
...
competition_round_insert = await conn.execute(
    CompetitionRound.insert()
                    .values(CompetitionId=competition_id,
                            RoundId=round_id))
competition_round_row = await competition_round_insert.fetchone()

Seems like it is not possible to insert the composite primary key as values... but how to insert key in such case?似乎无法将复合主键作为值插入...但是在这种情况下如何插入键? Unfortunately I have not found some example in SQLAlchemy documentation... (不幸的是,我没有在 SQLAlchemy 文档中找到一些示例......(

From what I understand of the documentation, SQLAlchemy only implicitly returns autoincrement primary keys, which composite PKs specifically are not:据我对文档的了解,SQLAlchemy 仅隐式返回autoincrement主键,而复合 PK 不是:

autoincrement 自动递增

The autoincrement flag now defaults to "auto" which indicates autoincrement semantics by default for single-column integer primary keys only; autoincrement 标志现在默认为“auto”,默认情况下仅指示单列 integer 主键的自动增量语义; for composite (multi-column) primary keys, autoincrement is never implicitly enabled;对于复合(多列)主键,永远不会隐式启用自动增量; as always, autoincrement=True will allow for at most one of those columns to be an “autoincrement” column.与往常一样,autoincrement=True 将允许最多这些列中的一个是“自动增量”列。 autoincrement=True may also be set on a Column that has an explicit client-side or server-side default, subject to limitations of the backend database and dialect. autoincrement=True 也可以设置在具有显式客户端或服务器端默认值的 Column 上,受后端数据库和方言的限制。

inserted_primary_key 插入主键

Note that primary key columns which specify a server_default clause, or otherwise do not qualify as “autoincrement” columns (see the notes at Column), and were generated using the database-side default, will appear in this list as None unless the backend supports “returning” and the insert statement executed with the “implicit returning” enabled.请注意,指定 server_default 子句或不符合“自动增量”列(请参阅 Column 中的注释)并使用数据库端默认值生成的主键列将在此列表中显示为 None ,除非后端支持“返回”和启用“隐式返回”时执行的插入语句。

Meaning you probably want to use an explicit returning clause on your insert.这意味着您可能想在插入中使用显式返回子句 Not that I really see the point though, you obviously have the relevant values since you inserted them.并不是说我真的明白这一点,你显然有相关的价值,因为你插入了它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM