python - 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()
]
解决方案
字典键在 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()
]
推荐阅读
- ios - SceneKit - 渲染节点始终具有相同的屏幕空间大小
- python - 如何将表格格式的结果转换为python中的列表?
- javascript - puppeteer 如何等待所有重定向
- ios - IOS/Objective-C:nil 和 null 的 JSON 响应测试
- angular - 如何创建要在不同组件/路线中扩展的数据模型
- javascript - 数据表子行问题
- node.js - 车把不渲染
- curl - curl 无法解析子域,但浏览器可以
- xaml - Xamarin Forms 中的全局标记扩展
- java - 在 map().flatMap() 上使用单个 flatMap() 会更好吗?