【发布时间】: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_update 内 set_ 中原始冲突行的值?
谢谢
【问题讨论】:
标签: python postgresql sqlalchemy upsert