一尘不染

如何使用SQLAlchemy仅选择一列?

flask

我只想通过“ where子句”从数据库中选择(并返回)一个字段。代码是:

from sqlalchemy.orm import load_only
    @application.route("/user", methods=['GET', 'POST'])
    def user():
        user_id = session.query(User, User.validation==request.cookies.get("validation")).options(load_only("id"))
        session.commit()
        return user_id

这将失败,并且回溯是:

File "/Library/Python/2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Library/Python/2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/Library/Python/2.7/site-packages/flask/app.py", line 1478, in full_dispatch_request
response = self.make_response(rv)
File "/Library/Python/2.7/site-packages/flask/app.py", line 1577, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 841, in force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/Library/Python/2.7/site-packages/werkzeug/wrappers.py", line 57, in _run_wsgi_app
return _run_wsgi_app(*args)
File "/Library/Python/2.7/site-packages/werkzeug/test.py", line 867, in run_wsgi_app
app_rv = app(environ, start_response)
TypeError: 'Query' object is not callable

如何选择并仅返回“ id”列?我也尝试了其他几种方法,但也失败了。是“ load_only”正确的选项吗?


阅读 517

收藏
2020-04-07

共1个答案

一尘不染

一个Query对象接受实体查询作为位置参数,所以只是通过它User.id

user_id = session.query(User.id).\
        filter(User.validation == request.cookies.get("validation")).\
        scalar()

scalar()返回第一个结果的第一个元素;如果未找到任何行,则返回None。它为多行引发MultipleResultsFound异常。

load_only()表示仅应加载实体的给定基于列的属性,而其他所有期望标识的属性将被延迟。如果以后确实需要整个User模型对象,则可以采用这种方法。在这种情况下,你的原始查询必须更改为:

user = session.query(User).\
        filter(User.validation == request.cookies.get("validation")).\
        options(load_only("id")).\
        one()

one()仅返回一个结果或引发异常(0个或多个1个结果)。如果你接受None“没有找到用户”作为有效的返回值,请使用one_or_none()。
请注意,谓词(WHERE子句的条件)不应Query作为实体传递给对象,而应与一起添加filter()

最重要的是,Flask中的视图期望你返回以下之一:

  • a valid response object
  • a string
  • a (response, status, headers) tuple
  • a WSGI application

机器会将响应对象,字符串或元组以外的任何内容都视为WSGI应用程序。在你的原始代码中,Query由于缺少对scalar()此类的调用,你返回了一个对象,然后将该对象视为WSGI应用程序。

2020-04-07