如何在SqlAlchemy中创建对象时绑定事件? [英] How to bind event on create of object in SqlAlchemy?

查看:68
本文介绍了如何在SqlAlchemy中创建对象时绑定事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表 A B .在表 A 中创建新行之后,我需要在表 B 中创建一行(具有 ForeignKey 引用).

I have two tables A and B. I need to create a row in table B (with ForeignKey reference), after I create a new row in table A.

例如:

class A(db.Model):
    __tablename__ = 'a'

    id = Column(BigInteger, primary_key=True)
    ...

class B(db.Model):
    __tablename__ = 'b'

    id = Column(BigInteger, primary_key=True)
    a_id = Column(BigInteger, ForeignKey('a.id'), nullable=False, index=True)
    ...

在SA中,这种情况的最佳解决方案是什么?

What is the best solution for this case in SA?

我听说过事件,但是不了解如何在这种情况下以最佳方式使用事件.

I heard about events, but can't understand how to use them the best way in this case.

推荐答案

一个示例事件:

def update_slug(mapper, connection, target):
    target.slug = slugify(target.name)
    if target.name_en:
        target.slug_en = slugify(target.name_en)

event.listen(Post, 'before_insert', update_slug_with_date)
event.listen(Post, 'before_update', update_slug_with_date)

您只需定义一个函数.您需要将其标记为一个事件(最后两行),只是在您的情况下,它将在A模型上是"after_insert",并且可能是"after update".在该函数中,您可以执行以下操作:

You just define a function. You need to mark it as an event (last two lines), just in your case it will be 'after_insert' and probably 'after update' on the A model. In the function you can do something like this :

b = B()
b.a = target
b.save()

目标是引发事件的实例.

target here is the instance on which event is being raised.

根据评论进行编辑以标记正确的答案:根据文档,您无法在事件中执行此操作,而只能在SessionEvents.after_flush中执行.您应该查看以下文档: http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.MapperEvents.after_insert

EDIT FROM THE COMMENT TO MARK THE RIGHT ANSWER : According to docs you can't do it in event but in SessionEvents.after_flush . You should check out the docs : http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.MapperEvents.after_insert

这篇关于如何在SqlAlchemy中创建对象时绑定事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆