SQLAlchemy不提交更新

时间:2018-12-11 14:16:04

标签: python python-3.x sqlalchemy

当尝试使用SQLalchemy进行更新时,我得到了一些意外的行为。

我有一个像这样的对象。

updatedINfo = {'id': 1, 'type': 'NewData'}
# The ID is an id from the table, the 'type' is a column from that table
# The 'NewData' is what needs to replace whatever is currently stored in
# 'type' column.

因为我希望此函数可重用,而不必对列名进行硬编码,所以我想我可以做这样的事情;

# Find the event first
the_event = db.query(EventsPending).filter(EventsPending.id == updatedInfo.get('id')).one_or_none()

# If it returns None, something went wrong
if not the_event:
    return {'Error': 'Something went wrong..'}

# Take the id out of the JSON post
del updatedInfo['id']

# Turn our db query into a dict
event_dict = the_event.as_dict()

# Set the keys for cross checking
for key in event_dict.keys():
    if key in updatedInfo.keys():
        the_event.__dict__[key] = updatedInfo.get(key)
        print(the_event.type)
        # THIS PRINTS THE UPDATED TYPE
        print(the_event.as_dict())
        # THIS ALSO PRINTS THE UPDATED TYPE

       db.commit()
       print(the_event.type)
       # HOWEVER THIS PRINTS THE OLD TYPE AFTER THE COMMIT
       # The commit does not make it to the database
       # I see no errors, and logging shows no useful info

很明显,我可以通过使用不同的类型进行编码来解决此问题,但实际上看起来很丑陋且效率低下。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

对于遇到此问题的任何人。您需要

setattr(the_event, key, data)
# the_event being the sqlalchemy object
# key being the column name
# data being the new value

希望这对某人有帮助。