如何侦听特定模型的创建并基于此创建新模型(在不同的表上)? [英] How can I listen for the creation of a specific model and create a new one (on a different table) based on this?

查看:65
本文介绍了如何侦听特定模型的创建并基于此创建新模型(在不同的表上)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 模型,该模型具有 referral_key 属性。我想在创建用户后创建 ReferralKeyRecord 。我看了无数的文档和StackExchange都无济于事。

I have a User model with a referral_key attribute. I'd like to create a ReferralKeyRecord upon creation of a user. I've read tons of documentation and StackExchange to no avail.

答案使用 after_insert(),但我没有尝试更改或验证要插入的类;我正在尝试从完全不同的模型添加新对象,并且不支持 session.add()

This answer uses after_insert(), but I am not trying to alter or validate the class which is being inserted; I am trying to add a new object from a completely different model—and session.add() isn't supported.

答案更接近我想要什么,但是被接受的答案(最终)使用了 after_flush(),这太笼统了。我不想听数据库以某种方式更新时引发的事件。我希望在创建特定模型时将其触发。

This answer is closer to what I want, but the accepted answer (ultimately) uses after_flush(), which is far too general. I don't want to listen to events thrown whenever the DB is updated somehow. I want it to fire off when a specific model is created.

还有类似以下内容的东西...

And something like the following...

@event.listens_for(User, 'after_flush')
def create_referral_record(mapper, connection, target):
    session.add(ReferralRecord(key=instances.referral_key))
    session.commit()

...导致目标'<类'models.User'> 没有此类事件'after_flush'。我浏览了SQLAlchemy的文档(核心事件和ORM事件),没有发现表明已创建特定模型的事件。 Mapper事件中最接近的是 after_insert 方法,而Session事件中最接近的是 after_flush()方法。我想这是一件很平常的事情,如果没有一件容易的事要听,我会感到惊讶。我假设它是这样的:

... results in No such event 'after_flush' for target '<class 'models.User'>. I've looked through SQLAlchemy's documentation (the core events and the ORM events) and see no events that indicate a specific model has been created. The closest thing in Mapper events is the after_insert method, and the closest thing in Session events is the after_flush() method. I imagine this is a pretty common thing to need to do, and would thus be surprised if there wasn't an easy event to listen to. I assume it'd be something like:

@event.listens_for(User, 'on_creation')
def create_referral_record(session, instance):
    record = ReferralRecord(key=instance.referral_key)
    session.add(record)
    session.commit()

有人比我知道吗?

推荐答案

还是为什么不在 User 构造函数中创建 Referral

Or why not create the Referral inside the User constructor?

from sqlalchemy.orm import Session, relationship, Mapper
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, ForeignKey, create_engine, event


Base = declarative_base()


class User(Base):
    __tablename__ = 'user'

    def __init__(self):
        self.referral = Referral()

    id = Column(Integer(), primary_key=True)    
    referral = relationship('Referral', uselist=False)


class Referral(Base):
    __tablename__ = 'referral'
    id = Column(Integer(), primary_key=True)
    user_id = Column(Integer(), ForeignKey('user.id'), nullable=False)


engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
session = Session(bind=engine)

session.add(User())
session.commit()

print(session.query(User).all())
print(session.query(Referral).all())

这篇关于如何侦听特定模型的创建并基于此创建新模型(在不同的表上)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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