首页 > 解决方案 > django raw query根据select查询返回无序的dict位置

问题描述

例如,我有一个查询select a, b, c, d from table。为什么字典有时会返回 [{'b': 2}, {'a': 1}, {'d': 4}] ....] 等等。我想要它 [{'a': 1}, {'b': 2}, {'c': 3}, ....] 根据选择查询中的位置。

db.execute(query)
data = dictfetchall(db)
def dictfetchall(cursor):
    # Return all rows from a cursor as a dict
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]

标签: pythonmysqldjango

解决方案


字典键在 Python 3.6 之前一直是无序的,其中 CPython 的字典实现保持插入顺序,并且在 Python 3.7 字典顺序成为官方保证。

由于您使用的是 Python 3.5,其中 dict 键是无序的,因此典型的替代方法是使用collections.OrderedDict

from collections import OrderedDict

def dictfetchall(cursor):
    columns = [col[0] for col in cursor.description]
    return [
        OrderedDict(zip(columns, row))
        for row in cursor.fetchall()
    ]

推荐阅读