Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

while working on my Python project (my first app), I ran into an issue when running a query against the database: I get as a result a list of tuples containing a single value, like: [(value1, ), (value2, )] The tables involved have a Many to Many relationships, the ORM is SQLAlchemy.

My solution is to use a foreach loop:

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

For a better understanding, you can have a look here: https://github.com/Deviad/adhesive/blob/master/theroot/users_bundle/helpers/users_and_roles.py

I am looking for a better approach as I know that foreach loops are time-consuming.

Thank you.

like image 470
Davide Pugliese Avatar asked Jan 03 '23 22:01

Davide Pugliese


1 Answers

Assuming the_roles is the list of tuples with one element (in your example you obtain it from database, but it doesn't matter for response object generating) like

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

then we can generate response object using list comprehension and tuple unpacking

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

Finally your get_user_role can be rewritten like

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]
like image 159
Azat Ibrakov Avatar answered Jan 14 '23 00:01

Azat Ibrakov