【问题标题】:How to append to a list in on conflict_do_update in SQLAlchemy?如何附加到 SQLAlchemy 中的 conflict_do_update 列表中?
【发布时间】:2021-04-30 06:19:48
【问题描述】:

型号:

class Example(Base):
    __tablename__ = "example"

    create_time = Column(DateTime, server_default=func.now())
    time_stamps = Column(MutableList.as_mutable(ARRAY(DateTime)), server_default="{}")
    update_time = Column(DateTime, server_default=func.now())

现在当我插入新示例时,我需要将新示例的create_time 附加到time_stamps ARRAY 中,然后我需要对其进行排序以获得最新时间并将该时间设置为新的update_time

我设法分开做

def update_record(db: Session, create_time: datetime, db_record: Example):
    db_record.time_stamps.append(create_time)
    sorted_times = sorted(db_record.time_stamps, reverse=True)
    db_record.update_time = sorted_times[0]
    db_record.time_stamps = sorted_times
    db.commit()

但我需要使用INSERT ON CONFLICT UPDATE 子句以原子方式进行。

到目前为止我有:

db_dict = {"create_time": record.create_time,
          "time_stamps": [record.create_time],
          "update_time": record.create_time}

stm = insert(Example).values(db_dict)
do_update_stm = stm.on_conflict_do_update(constraint='my_unique_constraint',
                                         set_=dict(??)

我的问题是如何访问并附加到 SQLAlchemy 中 conflict_do_updateset_ 中原始冲突行的值?

谢谢

【问题讨论】:

    标签: python postgresql sqlalchemy upsert


    【解决方案1】:

    最后我绕过了 SQLAlchemy,编写了一个文本查询,我可以使用这个语法附加到 ARRAY

    .. DO UPDATE SET time_stamps = example.time_stamps || EXCLUDED.create_time,
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 2019-09-21
      • 2017-10-20
      • 2018-04-25
      • 2023-01-25
      • 2019-02-26
      • 1970-01-01
      相关资源
      最近更新 更多