gpt4 book ai didi

python - SQLAlchemy 核心从 (0..1) 一对一关系中的连接表中选择引发歧义名称 InvalidRequestError

转载 作者:行者123 更新时间:2023-12-01 04:23:57 24 4
gpt4 key购买 nike

我正在使用 SQLAlchemy 核心(版本 1.13.12)定义两个必须具有一对一 (0..1) 关系的表:

things = sa.Table(
"things",
metadata,
sa.Column("sid", sa.Integer, primary_key=True),
sa.Column("info", sa.String)
)

thingsextra = sa.Table(
"thingsextra",
metadata,
sa.Column("sid", sa.Integer, sa.ForeignKey(things.c.sid), primary_key=True),
sa.Column("moreinfo", sa.String)

fullthings = sa.join(things, thingsextra, isouter=True)

我在“things”表中插入了一个项目,但没有在“thingsextra”中插入。然后我尝试选择左外连接:
query = fullthings.select().where(things.c.sid == sid)
result = conn.execute(query).fetchone()

我收到以下异常:
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'sid' in result set column descriptions

看起来它没有将定义的 ForeignKey 理解为同一件事,但我不知道如何解决它。

最佳答案

执行查询时不会发生报告的错误(查询本身没问题)但尝试访问时不会发生sid结果栏:

>>> result.sid
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlalchemy.exc.InvalidRequestError: Ambiguous column name 'sid' in result set column descriptions

原因是您的 SELECT 包含具有相同 sid 的两列名称,来自 things表和另一个来自 thingsextra因为你加入了他们。您可以通过显示 result.keys() 来检查它。

>>> result.keys()
['sid', 'info', 'sid', 'moreinfo']

如专栏 sidthingsextra是来自 sid 的外键在 things您可以从 SELECT 中删除此列,使其只包含一个 sid柱子。您可以通过使用 with_only_columns 在查询中选择您需要的列来实现。

>>> query = fullthings.select().with_only_columns([things.c.sid, things.c.info, thingsextra.c.moreinfo]).where(things.c.sid == 1)
>>> result = connection.execute(query).fetchone()
>>> result.keys()
['sid', 'info', 'moreinfo']
>>> result.sid
1

关于python - SQLAlchemy 核心从 (0..1) 一对一关系中的连接表中选择引发歧义名称 InvalidRequestError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599387/

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