You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python和Django从数据库表取数并在HTML文件中结构化展示?

从PostgreSQL取数据并在Django中展示到HTML的最优方案

1. 配置PostgreSQL数据库连接

先替换Django settings.py 里的默认SQLite配置,改成PostgreSQL连接:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '你的数据库名',
        'USER': '数据库用户名',
        'PASSWORD': '数据库密码',
        'HOST': 'localhost',  # 按需改成你的数据库地址
        'PORT': '5432',       # PostgreSQL默认端口
    }
}

提前安装依赖包:pip install psycopg2-binary

2. 映射数据库表到Django模型

如果已有现成的PostgreSQL表,用命令自动生成模型:

python manage.py inspectdb > app_name/models.py

如果是新建表,直接在models.py里定义模型(示例为书籍表):

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    publication_date = models.DateField()

    class Meta:
        db_table = 'books'  # 指定对应PostgreSQL中的表名

新建表需执行迁移生效:

python manage.py makemigrations
python manage.py migrate

3. 在视图中查询数据

用Django ORM从数据库拉取数据,传递给模板:

from django.shortcuts import render
from .models import Book

def book_list(request):
    # 可按需加过滤条件,比如Book.objects.filter(author="XXX")
    books = Book.objects.all()
    return render(request, 'book_list.html', {'books': books})

4. 配置URL路由

在项目或app的urls.py中添加路由映射:

from django.urls import path
from . import views

urlpatterns = [
    path('books/', views.book_list, name='book_list'),
]

5. 编写HTML模板展示结构化数据

在templates文件夹下创建book_list.html,用Django模板语言循环渲染:

<!DOCTYPE html>
<html>
<head>
    <title>书籍列表</title>
    <style>
        table { border-collapse: collapse; width: 80%; margin: 20px auto; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h1>书籍列表</h1>
    <table>
        <tr>
            <th>书名</th>
            <th>作者</th>
            <th>出版日期</th>
        </tr>
        {% for book in books %}
        <tr>
            <td>{{ book.title }}</td>
            <td>{{ book.author }}</td>
            <td>{{ book.publication_date }}</td>
        </tr>
        {% empty %}
        <tr>
            <td colspan="3">暂无书籍数据</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

6. 测试运行

启动Django开发服务器:

python manage.py runserver

访问http://localhost:8000/books/即可看到结构化展示的数据。

教学级优化建议

  • 查询优化:关联表查询时用select_related/prefetch_related避免N+1查询,比如Book.objects.all().select_related('publisher')
  • 分页处理:数据量大时用Django Paginator实现分页,降低页面负载
  • 模板复用:把通用页面片段(如页眉、页脚)抽成独立模板,用{% include %}或模板继承减少重复代码

内容的提问来源于stack exchange,提问作者user13562472

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 00:31:38