2017-06-04 186 views
1

在处理我的Python项目(我的第一个应用程序)时,我在对数据库运行查询时遇到了一个问题: 我得到一个列表包含单个值的元组,如: [(value1,),(value2,)] 涉及的表具有多对多关系,ORM是SQLAlchemy。Python - 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循环是耗时的。

谢谢。

+0

为什么不在'the_roles'中扮演角色? –

+0

@AzatIbrakov,因为我有一个集合列表而不是基元类型列表,原子元素。 –

+0

我没有看到集这里 –

回答

3

假设the_roles的元组的一个元素的列表(你从数据库中获取它在你的榜样,但不要紧,response对象发生),如

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

那么我们就可以用产生response对象list comprehensiontuple 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] 
+0

谢谢,它就像一个魅力! –

+0

@DavidePugliese:我很高兴帮助,顺便说一句,你也可以[upvote answers](https://stackoverflow.com/help/someone-answers) –

+0

还没有足够的回购积极upvote。我会对SO更加积极。 –