gpt4 book ai didi

python - SQLALCHEMY:如何在flask_sqlalchemy-SQLalchemy 中使用@events.listens_for

转载 作者:行者123 更新时间:2023-12-03 13:32:08 26 4
gpt4 key购买 nike

我需要一些帮助来自动化 sqlalchemy 中的一些任务。
当新用户在我的网站上注册时,我需要添加 5 名人员。

我想使用 sqlalchemy events因为如果我可以让它工作,它将在以后的其他自动化中派上用场。

我正在关注 Miguel Grinberg 先生关于如何制作 flask 的教程
申请并定义我的模型(db.Model 不是 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

关于python - SQLALCHEMY:如何在flask_sqlalchemy-SQLalchemy 中使用@events.listens_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41249045/

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