从PostgreSQL获取数据到Django并以html

时间:2018-06-07 21:37:25

标签: python django postgresql

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

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',
    }
}

2 个答案:

答案 0 :(得分:4)

django对db使用ORM(与对象相关的maping)。它在django中被称为Model

这意味着,您应该为您的数据库表和方案设置Model类,并且django会自动为模型创建sql - 所以您不需要执行sql job,直到您需要。

以下是模型示例。 (文档中的示例)

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

Django创建数据库表,如...

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

在答案中很难解释所有,所以你必须看看django官方文档。在完成以下教程之后(它编写得很好!),您可以理解django - 至少,请按照教程进行操作。

以下是一些帮助网站。

答案 1 :(得分:0)

您应该使用Django模块,即models.py(由django.db.models.Model继承),该模块根据您的选择创建数据字段,并在您按Enter键时将其迁移到数据库(在您的情况下为Postgresql)通过输入不带字符串的“ python manage.py migration”。可能由于这个事实,您无法从数据库获得任何东西。