Django原始查询根据选择查询返回无序字典位置

时间:2019-04-11 04:24:42

标签: python mysql django

我有一个查询,例如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()
    ]

1 个答案:

答案 0 :(得分:0)

在3.6版之前,Dicts键一直是无序的,直到3.6版为止,CPython的dict实现保持插入顺序,而在Python 3.7中,dict顺序得到正式保证。

由于您使用的是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()
    ]
相关问题