SQLAlchemy使用合并更新PostgreSQL数组不起作用 [英] SQLAlchemy update PostgreSQL array using merge not work
问题描述
我正在使用SQLAlchemy访问PostgreSQL数据库,并且我定义了这样的对象:
I'm using SQLAlchemy to access PostgreSQL database, and I defined the object like this:
class SessionLog(Base):
__tablename__ = 'session_log'
id = Column(Integer, primary_key=True)
recordFile = Column('record_file', String(128))
appSrcPorts = Column('app_src_ports', ARRAY(Integer))
info5 = Column('info5', String(100))
,然后选择并更新session_log表,如下所示:
and I select and update the session_log table like this:
session = Session()
sessionLog = session.query(SessionLog).filter_by(id=sessionLogId).first()
sessionLog.appSrcPorts.append(1)
session.merge(sessionLog)
session.commit()
但是在我调用merge()并提交后,'app_src_ports'列没有更新很奇怪()。
并且我找到一种使其工作的丑陋方法,在append()行之前,添加以下内容:
But it is weird the column 'app_src_ports' not update after I called merge() and commit(). And I find a ugly way to make it work, before the append() line, add this:
sessionLog.appSrcPorts = list(sessionLog.appSrcPorts)
任何人都可以告诉我为什么?
Anyone can tell me why?
推荐答案
SQLAlchemy ORM依赖于事件检测,以告知何时某些数据已更改,从而确定何时需要刷新数据。在这种情况下,您要就地更改Python数组的值,默认情况下不会产生任何事件。为了使其正常工作,您需要使用可变扩展名结合ARRAY类型(以及发送这些事件的 list
子类),以便将更改作为与父相关的事件发送SessionLog
对象。
the SQLAlchemy ORM relies upon detection of events in order to tell when some data has changed, and thus when data needs to be flushed. in this case, you are altering the Python array value in-place, which does not by default produce any events. In order for this to work you need to use the mutable extension in conjunction with the ARRAY type (as well as a list
subclass which sends these events) in order for changes to be sent as events related to the parent SessionLog
object.
这篇关于SQLAlchemy使用合并更新PostgreSQL数组不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!