gpt4 book ai didi

python - SQLAlchemy 'on_conflict_do_update' 不更新

转载 作者:行者123 更新时间:2023-11-28 19:00:39 26 4
gpt4 key购买 nike

我有以下代码,我想对其进行更新插入:

def add_electricity_reading(
*, period_usage, period_started_at, is_estimated, customer_pk
):
from sqlalchemy.dialects.postgresql import insert

values = dict(
customer_pk=customer_pk,
period_usage=period_usage,
period_started_at=period_started_at,
is_estimated=is_estimated,
)
insert_stmt = insert(ElectricityMeterReading).values(**values)
do_update_stmt = insert_stmt.on_conflict_do_update(
constraint=ElectricityMeterReading.__table_args__[0].name,
set_=dict(
period_usage=period_usage,
period_started_at=period_started_at,
is_estimated=is_estimated,
)
)
conn = DBSession.connection()
conn.execute(do_update_stmt)

return DBSession.query(ElectricityMeterReading).filter_by(**dict(
period_usage=period_usage,
period_started_at=period_started_at,
customer_pk=customer_pk,
is_estimated=is_estimated,
)).one()

def test_updates_existing_record_for_started_at_if_already_exists():
started_at = datetime.now(timezone.utc)
existing = add_electricity_reading(
period_usage=0.102,
customer_pk=customer.pk,
period_started_at=started_at,
is_estimated=True,
)
started_at = existing.period_started_at
reading = add_electricity_reading(
period_usage=0.200,
customer_pk=customer.pk,
period_started_at=started_at,
is_estimated=True,
)

# existing record was updated
assert reading.period_usage == 0.200
assert reading.id == existing.id

在我的测试中,当我使用 period_usage=0.102 添加现有记录,然后再次执行查询但更改为 period_usage=0.2 时。当底部的最终查询返回记录时,period_usage 仍然是 0.102。

知道为什么会这样吗?

最佳答案

此行为在 "What does the Session do?" 下的“ session 基础”中进行了解释 session 保存对已加载到名为 identity map 的结构中的对象的引用。 ,因此确保在 session 的生命周期内,每个主键值一次只存在 1 个唯一对象。您可以在自己的代码中使用以下断言来验证这一点:

assert existing is reading

Core您正在执行的插入(或更新)语句不会使 session 与数据库中发生的更改保持同步,例如 Query.update()做。为了获取新值,您可以 expire唯一对象的 ORM 加载状态:

DBSession.expire(existing)  # or reading, does not matter

# existing record was updated
assert reading.period_usage == 0.200
assert reading.id == existing.id

关于python - SQLAlchemy 'on_conflict_do_update' 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52947219/

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