Python 如何使用 SQLAlchemy 仅选择一列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37133774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I select only one column using SQLAlchemy?
提问by user1903663
I want to select (and return) one field only from my database with a "where clause". The code is:
我只想从我的数据库中使用“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
This fails and the traceback is:
这失败了,回溯是:
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
How can I select and return just the "id" column? I have tried several other ways too but also with failure. Is "load_only" the correct option?
如何仅选择并返回“id”列?我也尝试过其他几种方法,但也都失败了。“load_only”是正确的选项吗?
回答by Ilja Everil?
A Query
object accepts entities to query as positional arguments, so just pass it User.id
:
一个Query
对象接受实体查询作为位置参数,所以只是通过它User.id
:
user_id = session.query(User.id).\
filter(User.validation == request.cookies.get("validation")).\
scalar()
scalar()
returns the first element of the first result or None, if no rows were found. It raises MultipleResultsFound exception for multiple rows.
scalar()
如果未找到行,则返回第一个结果的第一个元素或 None。它为多行引发 MultipleResultsFound 异常。
load_only()
indicates that only the given column-based attributes of an entity should be loaded and all others, expect the identity, will be deferred. If you do need the whole User
model object later, this can be the way to go. In that case your original query has to change to:
load_only()
表示仅应加载实体的给定基于列的属性,而所有其他属性(除了标识)将被推迟。如果您以后确实需要整个User
模型对象,这可能是要走的路。在这种情况下,您的原始查询必须更改为:
user = session.query(User).\
filter(User.validation == request.cookies.get("validation")).\
options(load_only("id")).\
one()
one()
returns exactly one result or raises an exception (0 or more than 1 result). If you accept None
as a valid return value for "no user found", use one_or_none()
.
one()
只返回一个结果或引发异常(0 个或 1 个以上的结果)。如果您接受None
“未找到用户”的有效返回值,请使用one_or_none()
.
Note that predicates, the criteria of the WHERE clause, should not be passed to the Query
object as entities, but added with filter()
.
请注意,谓词,即 WHERE 子句的标准,不应Query
作为实体传递给对象,而应添加filter()
.
To top it off, views in Flask expect that you return one of:
最重要的是,Flask 中的视图期望您返回以下之一:
- a valid response object
- a string
- a
(response, status, headers)
tuple - a WSGI application
- 有效的响应对象
- 一个字符串
- 一个
(response, status, headers)
元组 - 一个 WSGI 应用程序
The machinery will treat anything other than a response object, a string or a tuple as a WSGI application. In your original code you returned a Query
object because of the missing call to scalar()
or such and this was then treated as a WSGI app.
该机制会将响应对象、字符串或元组以外的任何内容视为 WSGI 应用程序。在您的原始代码中,您Query
由于缺少对scalar()
等的调用而返回了一个对象,然后将其视为 WSGI 应用程序。
回答by Tkingovr
You would have to do something along these lines:
您必须按照以下方式做一些事情:
session.query(Table.col1).filter(User.name=='Name')
回答by ciacicode
To query the content of one column instead of the entire table flask-sqlalchemy, which I suppose can give you a hint about sqlalchemy itself would work gets you to query the session as you are doing, with a different syntax.
要查询一列的内容而不是整个表flask-sqlalchemy,我想这可以为您提供有关sqlalchemy 本身的提示,可以让您在执行时使用不同的语法查询会话。
If your table looks something like:
如果您的表看起来像:
class User(...):
id = db.Column(db.Integer, primary_key=True)
...
You can query it with:
您可以通过以下方式查询:
user_ids = session.query(User.id)
all_ids = user_ids.all()
This returns a list of all User Ids.
这将返回所有用户 ID 的列表。
回答by Alexey Smirnov
The problem has nothing to do with queries and db connection. Inside @application.route("/user", methods=['GET', 'POST']) statement you return a user_id which is a result of a select from database. In Flask you should return something appropriate.
该问题与查询和数据库连接无关。在 @application.route("/user", methods=['GET', 'POST']) 语句中,您返回一个 user_id,它是从数据库中选择的结果。在 Flask 中,您应该返回一些适当的.