从PostgreSQL获取数据到Django并在htm中显示

2024-06-16 10:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我在PostgreSQL数据库中有一个表,包含两列ID和Name。我使用django框架从数据库中获取数据,并希望将数据显示到html页面中。问题是检索到的数据没有列名。它看起来是这样的,为了在html页面中使用它,它必须为每个元组都有一个键。

[(2, 'abc'), (3, 'subhi')] 

我试图获取列名,但它们只是没有数据的表列。以下是我的代码:

模型.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 shown, instead just indexes.
                # for most people this isn't very useful so we'll show you how to return
                # columns as a dictionary (hash) in the next example.
                pprint.pprint(records)
                print (type(records))

    print("Column names: {}\n".format(column_names))



if __name__ == "__main__":
    main()

视图.py

from django.http import Http404

from django.shortcuts import render
from  .models import main


def index (request):
    all_albums = main()
    return  render(request,'music/index.html',{ 'all_albums' :all_albums})

index.html索引

{%  if all_albums  %}

<ul>
    {%  for album in all_albums  %}
    <li> <a href="/music/{{ album}}/">{{ album }}</a></li>
    {% endfor %}
</ul>

{% else %}
<h3> You don't have any data</h3>

{%  endif %}

以及显示PostgreSQL连接的settings.py:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'music',
        'USER': 'postgres',
        'PASSWORD': 'subhi123',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

Tags: thedjangoinfromimportfornamesmain