为什么选择查询返回数据作为元组,我需要在python中的关联数组

问题描述 投票:0回答:1

我是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
python django
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.