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

Viewed 6882

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.

1 Answers
Related