gpt4 book ai didi

python - 是否可以在 SQLAlchemy 中创建一个可以创建父记录的事件监听器?

转载 作者:行者123 更新时间:2023-11-28 17:43:25 28 4
gpt4 key购买 nike

有两个表:父表和子表。我想创建一个事件监听器(“触发器”),如果 child 没有 parent ,它可以创建 parent 。

这是我尝试做的:

class parent(db.Model):
__tablename__ = 'parent'
id = db.Column(db.Integer, primary_key=True)
children = db.relationship("child", backref="parent",
cascade="all, delete-orphan",
passive_deletes=True)


class child(db.Model):
__tablename__ = 'child'
id = db.Column(db.Integer, primary_key=True)
parent_id = db.Column(db.Integer,
db.ForeignKey('parent.id', ondelete='CASCADE'),
nullable=False)


def create_parent(mapper, connection, target):
if not(target.parent):
target.parent = parent()

event.listen(child, 'before_insert', create_parent)

测试:

c = child()
db.session.add(c)
db.session.commit()

并得到以下警告和错误:

C:\Python27\x\lib\site-packages\sqlalchemy\orm\unitofwork.py:79: SAWarning: Usage of the 'related attribute set' operation is not currently supported within the execution stage of the flush process. Results may not be consistent.  Consider using alternative event listeners or connection-level operations instead.
sess._flush_warning("related attribute set")

C:\Python27\x\lib\site-packages\sqlalchemy\orm\unitofwork.py:37: SAWarning: Usage of the 'collection append' operation is not currently supported within the execution stage of the flush process. Results may not be consistent. Consider using alternative event listeners or connection-level operations instead.
sess._flush_warning("collection append")

sqlalchemy.exc.IntegrityError: (IntegrityError) null value in column "parent_id" violates not-null constraint
DETAIL: Failing row contains (1, null).
'INSERT INTO child (parent_id) VALUES (%(parent_id)s) RETURNING child.id' {'parent_id': None}

我在文档中发现这不能通过 before_insert 事件实现,但可以通过 before_flush 实现,但我不知道该怎么做。

最佳答案

同时我找到了解决这个问题的方法。

from sqlalchemy.orm.session import Session as SessionBase

def before_flush(session, flush_context, instances):
children = [c for c in session.new if isinstance(c, child)]
for c in children:
if not (c.parent):
c.parent = parent()

event.listen(SessionBase, "before_flush", before_flush)

如果有人发现这不是处理这种情况的正确方法,我将感谢您的意见。

关于python - 是否可以在 SQLAlchemy 中创建一个可以创建父记录的事件监听器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21344728/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com