Hay*_*mas 3 python sql sqlalchemy commit pickle
我在 sqlalchemy 中提交对 pickle 类型(列表)的更改时遇到问题。交付后它将表现得好像什么都没发生一样。
这是我尝试提交的功能:
def commit_move(game_id, player, move):
game = game_query(game_id)
if player == 'human':
game.human_spaces.append(move)
if player == 'ai':
game.ai_spaces.append(move)
game.available_spaces.remove(move)
print game.human_spaces
print game.ai_spaces
print game.available_spaces
print "----"
session.add(game)
session.commit()
Run Code Online (Sandbox Code Playgroud)
该表的设置方式如下:
class Game(Base):
__tablename__ = 'game'
id = Column(Integer, primary_key=True)
human_spaces = Column(PickleType)
ai_spaces = Column(PickleType)
available_spaces = Column(PickleType)
Run Code Online (Sandbox Code Playgroud)
这是我用来测试它的代码:
game_id = create_game()
print game_id
print get_available_spaces(game_id)
print get_human_spaces(game_id)
print get_ai_spaces(game_id)
print "---------"
commit_move(game_id, 'human', 7)
print get_available_spaces(game_id)
print get_human_spaces(game_id)
print get_ai_spaces(game_id)
Run Code Online (Sandbox Code Playgroud)
这就是老终端告诉我的内容:
1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[]
[]
---------
[7]
[]
[1, 2, 3, 4, 5, 6, 8, 9]
----
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[]
[]
Run Code Online (Sandbox Code Playgroud)
我确信我在这里缺少一些简单的东西,但任何帮助将不胜感激!
问题是 ORM 不会收到关于可变类型(如列表)内的更改的警报。因此,SQLAlchemy 提供了带有扩展的突变跟踪sqlalchemy.ext.mutable。
从文档中的示例来看,特别是参考类sqlalchemy.ext.mutable.MutableList,看起来列声明应该如下(例如):
human_spaces = Column(MutableList.as_mutable(PickleType))
Run Code Online (Sandbox Code Playgroud)
我引用该as_mutable方法的文档:“这建立了侦听器,将检测针对给定类型的 ORM 映射,并向这些映射添加突变事件跟踪器。”