在处理我的Python项目(我的第一个应用程序)时,我在对数据库运行查询时遇到了一个问题:我得到一个包含单个值的元组列表,如:[(value1,),(value2, )]所涉及的表具有多对多关系,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
Run Code Online (Sandbox Code Playgroud)
为了更好地理解,您可以在这里查看: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,)]
Run Code Online (Sandbox Code Playgroud)
然后我们可以response使用list comprehension和tuple unpacking生成对象
>>>response = [value for (value,) in the_roles]
>>>response
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)
最后你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]
Run Code Online (Sandbox Code Playgroud)