python - SQLAlchemy update objects tree
问题描述
I'm trying to build a tree of objects. The class looks like this:
class Node(BaseModel, db.Model):
'''Node model'''
__tablename__ = 'network_nodes'
id = Column(String(10), primary_key=True)
parent_id = Column(String(10), ForeignKey('network_nodes.id'))
parent = relationship("Node", foreign_keys=[parent_id], lazy='dynamic')
left_id = Column(String(10), ForeignKey('network_nodes.id'))
left = relationship("Node", foreign_keys=[parent_id], lazy='dynamic')
right_id = Column(String(10), ForeignKey('network_nodes.id'))
right = relationship("Node", foreign_keys=[parent_id], lazy='dynamic')
Whenever new leaf is added this code is executed:
node.left_id = element_id
left = Node(id=element_id, parent_id=node.id)
db.session.add(left)
And at some point I commit all changes with db.session.commit()
. At the commit()
point I see dirty and new objects in session. But commit fails with error:
(MySQLdb._exceptions.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (
db
.network_nodes
, CONSTRAINTnetwork_nodes_ibfk_2
FOREIGN KEY (left_id
) REFERENCESnetwork_nodes
(id
))') [SQL: UPDATE network_nodes SET left_id=%s, right_id=%s WHERE network_nodes.id = %s] [parameters: ('S5837124', 'S5839010', 'S5832131')]
I assume dirty objects are committed before new ones. Therefore left_id
refers to not yet existing record.
How can I make new object committed before dirty ones?
解决方案
How can I make new object committed before dirty ones?
You could add all the objects, flush the new ones, and then commit the whole batch:
left = Node(id=element_id, parent_id=node.id)
session.add(left)
node.left_id = element_id
session.flush(session.new)
session.commit()
推荐阅读
- python - Flutter video_player(仅限IOS/AVPlayer)使用fastapi不播放无扩展名的mp4文件
- node.js - 如何使用 ExpressJS 一个 API 调用下载多个文件
- flutter - Flutter/Dart:导航器路线总是将我带到 selectedIndex = 0 的主屏幕
- python - 多张图,而不是一张使用 Matplotlib
- python - Python - Pandas - 只删除只有数字的拆分,但如果它有字母则保持
- android - NativeScript:加载或拍照时出现java.lang.OutOfMemoryError
- vue.js - Vue 组合 API - 为什么它没有按预期工作
- html - 如何永久隐藏菜单项?
- list - 优化从带有文件夹的库中下载文件的脚本
- confluent-schema-registry - 如何删除主题级别的兼容性级别