Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to deal with sqlalchemy.util._collections.result?

I just want to execute the sql:

select distinct price from items

so I write sqlalchemy code like below:

result_list = session.query(func.distinct(items.price)).all()

In my db, there are only 2 distinct prices, so the result should be 100 and 200 for example.

However, it returns a list of sqlalchemy.util._collections.result. But what I want is a list of int, such as [100, 200]

Of course I can do like this:

int_list = [ x.price for x in result_list ]

But this "workaround " is so ugly.

So is there a function like to_base_type so that I can write code like this:

int_list = session.query(func.distinct(items.price)).to_base_type()

Thanks very much if anyone can help me

like image 278
ruiruige1991 Avatar asked Jan 12 '18 18:01

ruiruige1991


1 Answers

You can use the _asdict() method of the result class. An example would be

def get_dict_list_from_result(result):
    list_dict = []
    for i in result:
        i_dict = i._asdict()  # sqlalchemy.util._collections.result , has a method called _asdict()
        list_dict.append(i_dict)
    return list_dict
like image 79
Ronald Das Avatar answered Sep 17 '22 22:09

Ronald Das