python - 为什么选择查询将数据返回为元组,我需要 python 中的关联数组
问题描述
我是python新手,我正在研究models.py
,我可以看到它显示我的数据为元组,我需要关联数组,谁能帮我,这是我的代码,它显示我输出这个输出((1, "What's up?", datetime.datetime(2019, 4, 19, 7, 38, 6, 449735))
,我需要字段值数据
import datetime
from django.utils import timezone
from django.db import connection
from django.db import models
class Question():
@classmethod
def get_poll_question(cls):
with connection.cursor() as cursor:
db_table = "polls_question"
cursor.execute('SELECT * FROM '+db_table)
allquestion = cursor.fetchall()
return allquestion
解决方案
你可以试试这个
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()
]
class Question():
@classmethod
def get_poll_question(cls):
with connection.cursor() as cursor:
db_table = "polls_question"
cursor.execute('SELECT * FROM '+db_table)
allquestion = dictfetchall(cursor)
return allquestion
推荐阅读
- r - 提取/访问嵌入在 PDF 中的 XML 文件
- python - 使用 AES-128 的图像加密
- java - 使用 txt 文件填充多列 ListView (Android)
- reactjs - 如何在测试中避免 react.createElement 错误
- php - 高级自定义字段重复器正在正确返回除图像之外的所有内容
- c# - Net Core 2.2 到 Net Core 3.1 迁移错误
- kiwi-tcms - 如何将套件添加到 kiwi-tcms
- qml - QML:初始化空列表
- opencv - 如何使用opencv将已知对象的图像与该对象的3D模型对齐?
- python - 在列表中找到最小值时出错