我有以下代码,我想补充一下:

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

在我的测试中,我添加了一个带有cc*>的现有记录,然后再次执行查询,但是改为period_usage=0.102。当底部的最终查询返回记录时,period_usage仍然是0.102。
知道为什么会这样吗?

最佳答案

这种行为在"What does the Session do?"下的“会话基础”中解释,会话包含对它在一个名为identity map的结构中加载的对象的引用,因此确保每个会话期间的每个主键值只有1个唯一的对象存在。您可以在自己的代码中使用以下断言来验证这一点:

assert existing is reading

您正在执行的Coreinsert(或update)语句不会像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/

10-09 20:15