Home > OS >  Getting rows from SQLite as lists in a list
Getting rows from SQLite as lists in a list

Time:04-14

I have problems with getting the data from a SQLAlchemy database. I need the rows of the database as lists and all of them go together in a list. Needed format:

list_of_lists = [[value_of_row1_column1, value_of_row1_column2], 
            [value_of_row2_column1, value_of_row2_column2]] 

main.py:

    #list_sellers_format_needed = [[13.30570, 51.27430, "string1"], [13.30571, 52.27429, "string2"], [13.30565, 53.27436, "string3"]]
    list_sellers_db = Seller.query.all()
    final_list = []
    for i in list_sellers_db:
        final_list.append([i])
    print(final_list)


output Terminal:

    a list of lists in the format above

CodePudding user response:

SQLAlchemy methods like .all() return a list of Row objects. You can convert a Row object to a list by simply passing it to list():

qry = """\
SELECT 1 AS x, 'foo' AS y
UNION ALL 
SELECT 2 AS x, 'bar' AS y
"""
with engine.begin() as conn:
    results = conn.exec_driver_sql(qry).all()
    list_of_lists = [list(row) for row in results]
    print(list_of_lists)
    # [[1, 'foo'], [2, 'bar']]

CodePudding user response:

I found the solution finally. I will integrate it in the answer above:

list_sellers_db = Seller.query.all() final_list = [] for i in list_sellers_db: final_list.append([i])

print(final_list)

will do the job.

But still I have the same issue. Coming through flask sqlalchemy it is ginving me an error:

raise TypeError(f'Object of type {o.class.name} TypeError: Object of type Seller is not JSON serializable

  • Related