Python-SqlAlchemy : convert lists of tuples to list of atomic values

标签 python sqlalchemy

<分区>

在处理我的 Python 项目(我的第一个应用程序)时,我在对数据库运行查询时遇到了一个问题: 结果我得到一个包含单个值的元组列表,例如: [(值 1, ), (值 2, )] 涉及的表是多对多关系,ORM是SQLAlchemy。

我的解决方案是使用 foreach 循环:

def get_user_roles(user_id):

    the_roles = db.session.query(Role.role).filter(Role.users.any(id=user_id)).all()
    response = []
    length = len(the_roles)
    for key in range(length):
        the_roles[key] = list(the_roles[key])
        response.append(the_roles[key][0])

    return response

为了更好的理解,你可以看这里: https://github.com/Deviad/adhesive/blob/master/theroot/users_bundle/helpers/users_and_roles.py

我正在寻找更好的方法,因为我知道 foreach 循环很耗时。

谢谢。

最佳答案

假设 the_roles 是具有一个元素的元组列表(在您的示例中,您是从数据库中获取它的,但是对于生成response 对象并不重要),例如

>>>the_roles = [(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]

然后我们可以使用list comprehension生成response对象和 tuple unpacking

>>>response = [value for (value,) in the_roles]
>>>response
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

最后你的 get_user_role 可以重写为

def get_user_roles(user_id):
    the_roles = db.session.query(Role.role).filter(Role.users.any(id=user_id)).all()
    return [value for (value,) in the_roles]

关于Python-SqlAlchemy : convert lists of tuples to list of atomic values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44355850/

相关文章:

python - 如何使用 outlook web access 从 python 发送电子邮件?

python - 在 Flask + SQLAlchemy 中设置一对一关系

python - sqlalchemy:关闭声明式多态连接?

docker - SQLAlchemy + pymssql-无法从jupyter内核网关docker连接到sql db

python - Reportlab:更改边距后重建文档?

python - django django-allauth 将社交登录中的 extra_data 保存在信号中

python - 您将预测许多参数的非二进制值的问题称为什么?

python - 如何在 elasticsearch-dsl python 中启用 track_scores

python - Flask sqlalchemy - 仅使用实体 ID 插入多对多

mysql - 如何在 Flask-Sqlalchemy 中设置全局级别 group_concat_max_len ?