我在PostgreSQL数据库中有一个表,其中包含两列ID和Name.我使用django框架从数据库中获取数据,我想将数据显示到html页面.问题是检索到的数据没有列名.它看起来像这样,并且为了在html页面中使用它,它必须有一个每个元组的键.
[(2, 'abc'), (3, 'subhi')]
我试图获取列名称,但它们只是没有数据的表列.以下是我的代码:
models.py
import psycopg2
import pprint
def main():
conn_string = "host='localhost' dbname='music' user='postgres' password='subhi123'"
column_names = []
data_rows = []
with psycopg2.connect(conn_string) as connection:
with connection.cursor() as cursor:
cursor.execute("select id, name from music")
column_names = [desc[0] for desc in cursor.description]
for row in cursor:
data_rows.append(row)
records = cursor.fetchall()
# print out the records using pretty print
# note that the NAMES of the columns are not sh