首页 > 解决方案 > 为什么选择查询将数据返回为元组,我需要 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

标签: pythondjango

解决方案


你可以试试这个

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

推荐阅读