首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从PostgreSQL获取数据到Django并将其显示在html中。

从PostgreSQL获取数据到Django并将其显示在html中。
EN

Stack Overflow用户
提问于 2018-06-08 05:37:25
回答 1查看 10.5K关注 0票数 4

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

代码语言:javascript
复制
[(2, 'abc'), (3, 'subhi')] 

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

models.py

代码语言:javascript
复制
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()

views.py

代码语言:javascript
复制
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

代码语言:javascript
复制
{%  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:

代码语言:javascript
复制
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'music',
        'USER': 'postgres',
        'PASSWORD': 'subhi123',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50750513

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档