gpt4 book ai didi

python - 从 PostgreSQL 获取数据到 Django 并以 html 显示

转载 作者:太空狗 更新时间:2023-10-30 02:37:16 25 4
gpt4 key购买 nike

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

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

最佳答案

django 对数据库使用 ORM(对象相关映射)。它在 django 中称为 Model

这意味着,你应该为你的数据库表和方案制作 Model 类,django 会自动为模型制作 sql - 所以你不会做 sql 工作直到你需要。

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

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 - 所以至少,遵循教程。

这里有一些网站可以寻求帮助。

关于python - 从 PostgreSQL 获取数据到 Django 并以 html 显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50750513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com