convert sqlalchemy query result to a list of dicts

后端 未结 4 1427
慢半拍i
慢半拍i 2021-02-08 03:54

I want to have the result of my query converted to a list of dicts like this :

result_dict = [{\'category\': \'failure\', \'week\': \'1209\', \'stat\': \'tdc_ok         


        
相关标签:
4条回答
  • 2021-02-08 04:32

    This works now

    result_dict = [u._asdict() for u in my_query.all()]
    

    The reason is that u is not actually a tuple but a KeyedTuple.

    The correct answer on this thread also would be helpful

    0 讨论(0)
  • 2021-02-08 04:33

    Try

    result_dict = [u.__dict__ for u in my_query.all()]
    

    Besides what is the type of your result_dict before the for loop? It's behavior is rather strange.

    0 讨论(0)
  • 2021-02-08 04:34

    Not sure if this is because a few years have passed since the original post, but the following works for me (the others did not)...

    result_dict = [dict(u) for u in my_query.fetchall()]
    

    I am working in core, not ORM.

    0 讨论(0)
  • 2021-02-08 04:42

    There's no .all()

    You can try:

    result_dict = [u.__dict__ for u in my_query.fetchall()]
    
    0 讨论(0)
提交回复
热议问题