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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With