为什么选择查询将数据还原为元组,我需要在python中关联数组

时间:2019-04-26 07:20:08

标签: python django

我是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

1 个答案:

答案 0 :(得分:2)

您可以尝试

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