在 SQLAlchemy 中查询属性列表而不是元组 [英] Query for list of attribute instead of tuples in SQLAlchemy

查看:53
本文介绍了在 SQLAlchemy 中查询属性列表而不是元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查询模型的 id,并返回 (int,) 元组列表而不是 id 列表.有没有办法直接查询属性?

I'm querying for the ids of a model, and get a list of (int,) tuples back instead of a list of ids. Is there a way to query for the attribute directly?

result = session.query(MyModel.id).all()

我意识到这是可能的

results = [r for (r,) in results]

查询是否可以直接返回该表单,而不必自己处理?

Is it possible for the query to return that form directly, instead of having to process it myself?

推荐答案

当传入 ORM-instrumented 描述符(如列)时,每个结果都是一个命名元组,即使只有一列.您可以在列表推导式中使用列名来展平"列表(您可以删除 .all() 调用,迭代也可以检索对象):

When passing in ORM-instrumented descriptors such as a column, each result is a named tuple, even for just one column. You could use the column name in a list comprehension to 'flatten' the list (you can drop the .all() call, iteration retrieves the objects too):

result = [r.id for r in session.query(MyModel.id)]

或者在循环 for 循环时使用它是一个元组的事实并将其解包为目标的单元素元组:

or use the fact that it's a tuple when looping a for loop and unpack it to a single-element tuple of targets:

result = session.query(MyModel.id)
for id, in result:
    # do something with the id

后者也可用于列表推导式:

The latter could also be used in a list comprehension:

[id for id, in session.query(MyModel.id)]

您真的没有任何选项可以强制行结果只是单个 id 值.

You don't really have any options to force the row results to be just the single id value.

这篇关于在 SQLAlchemy 中查询属性列表而不是元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆