【问题标题】:SQLAlchemy query.all() behaviorSQLAlchemy query.all() 行为
【发布时间】:2017-03-09 00:01:43
【问题描述】:

在我的 SQLAlchemy 应用程序中打开一些调试后,我注意到的是这样的语句:

self.session.query(User).all()

似乎对表中的每一行都运行一个查询。

select * from user where id = 1

select * from user where id = 2.

select * from user where id = n.

我希望只发布一个简单的select * from user。这是预期的行为还是在我的应用程序中配置不当?

【问题讨论】:

  • 这不是预期的。请发布您的模型配置。
  • 同意。绝对不是预期的。延迟加载关系可能存在问题

标签: python-2.7 sqlalchemy flask-sqlalchemy


【解决方案1】:

因此,结果证明它与事务范围和 Flask_RESTPlus marshal_with 装饰器有关。我基本上有这个:

@api.marshal_with(User)
def get(self):
    with transaction_scope(current_app.dbsession):
        return self.user_service.get_users(), 200

transaction_scope 基本上限定了事务中与数据库的交互范围。

但是,这导致装饰器尝试在事务范围之外编组响应,因此它看到过时的对象并在处理它们时对其进行补水,从而导致大量查询。

我改成这样了:

def get(self):
    with transaction_scope(current_app.dbsession):
        return api.marshal(self.user_service.get_users(), User), 200

解决了这个问题。

TL;DR - marshal_with 装饰器在事务之外运行时有一些意外行为。

【讨论】:

    猜你喜欢
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-13
    • 2015-05-28
    • 1970-01-01
    • 2015-09-11
    • 2017-02-03
    相关资源
    最近更新 更多