【问题标题】:Python - SqlAlchemy: convert lists of tuples to list of atomic values [duplicate]Python - SqlAlchemy:将元组列表转换为原子值列表[重复]
【发布时间】:2018-01-27 05:14:28
【问题描述】:

在处理我的 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 循环很耗时。

谢谢。

【问题讨论】:

  • 为什么不for role in the_roles
  • @AzatIbrakov,因为我有一个集合列表,而不是原始类型原子元素的列表。
  • 我在这里看不到套装
  • 而集合列表本身就是一个列表,即可迭代
  • @AzatIbrakov 实际上是我得到的一个错误:TypeError: list indices must be integers or slices, not result

标签: python sqlalchemy


【解决方案1】:

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

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

然后我们可以使用list comprehensiontuple unpacking生成response对象

>>>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]

【讨论】:

    猜你喜欢
    • 2017-09-10
    • 2017-03-24
    • 2019-05-02
    • 2014-07-14
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2018-02-08
    • 2011-07-27
    相关资源
    最近更新 更多