SQLALCHEMY:如何在flask_sqlalChemy-SQLalChemy中使用@events.listens_for
问题描述
我需要一些帮助来自动执行sqlalChemical中的某些任务。 当一个新用户在我的网站上注册时,我需要添加5个人员。
我想使用sqlalChemicalevents
,因为如果我能让它正常工作,以后其他自动化就会派上用场。
我正在学习Miguel Grinberg先生关于如何制作烧瓶的教程 应用程序和定义我的模型(db.Model Not Base)。
我读到要使用@event.listens_for(User.__table__, "after_insert")
,我必须使用声明性基础。有什么办法可以绕过这件事吗?我的模型结构涉及近15个表!
class User(db.Model):
__tablename__ = "user"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
store = db.relationship('Store', uselist=False, backref="user")
@event.listens_for(User.__table__, "after_insert")
def add_personnel(*args, **kwargs):
for i in range(5):
db.session.add(Personnel,store_id = User.query.last().id)
db.session.commit()
return None
class Personnel(db.Model):
__tablename__ = "personnel"
id = db.Column(db.Integer, primary_key=True)
store_id = db.Column(db.Integer, db.ForeignKey('store.id'))
first_name = db.Column(db.String(64))
last_name = db.Column(db.String(64))
username = db.Column(db.String(64))
cell_phone = db.Column(db.Integer)
pin_number = db.Column(db.Integer)
email = db.Column(db.String(64))
orders = db.relationship("Order", backref='personnel', lazy='dynamic')
**TRACEBACK**
Traceback (most recent
call last):
File "manage.py", line 3, in <module>
from app.models import User
File "/home/#######/PycharmProjects/#######/app/models.py", line 62, in <module>
@event.listens_for(User.__table__, "after_insert")
File "/home/#######/PycharmProjects/#######//venv/local/lib/python2.7/site-packages/sqlalchemy/event/api.py", line 124, in decorate
listen(target, identifier, fn, *args, **kw)
File "/home/#######/PycharmProjects/#######/venv/local/lib/python2.7/site-packages/sqlalchemy/event/api.py", line 89, in listen
_event_key(target, identifier, fn).listen(*args, **kw)
File "/home/#######/PycharmProjects/#######/venv/local/lib/python2.7/site-packages/sqlalchemy/event/registry.py", line 194, in listen
dispatch_collection = getattr(target.dispatch, identifier)
File "/home/#######/PycharmProjects/#######/venv/local/lib/python2.7/site-packages/sqlalchemy/event/base.py", line 95, in __getattr__
raise AttributeError(name)
AttributeError: after_insert
解决方案
我使用参数中的连接使我像这样工作。
@db.event.listens_for(Order, "after_insert")
def insert_order_to_printer(mapper, connection, target):
po = PrinterOrder.__table__
connection.execute(po.insert().values(store_id=target.store_id, order_id=target.id, scenario=target.order_type))
其中订单为:
class Order(db.Model):
#stuff
相关文章