ListView
是Django的通用视图之一,它用于显示一个对象列表。这个视图将所有的对象作为一个上下文变量传递给模板。
1,创建应用
python manage.py startapp app3

2,注册应用
Test/Test/settings.py
Test/Test/urls.py

3,添加模型
Test/app3/models.py
from django.db import models
# Create your models here.
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
publication_date = models.DateField()

4,添加视图
Test/app3/views.py
from django.shortcuts import render
# Create your views here.
from django.views.generic import ListView
from .models import Book
class BookListView(ListView):
model = Book
context_object_name = 'books'
template_name = 'books/book_list.html'
5,添加HTML代码
Test/templates/books/book_list.html
<!-- 在templates/books/book_list.html中 -->
<!DOCTYPE html>
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>Book List</h1>
<ul>
{% for book in books %}
<li>{{ book.title }} by {{ book.author }} ({{ book.publication_date }})</li>
{% empty %}
<li>No books available.</li>
{% endfor %}
</ul>
</body>
</html>

6,添加路由地址
Test/app3/urls.py
from django.urls import path
from . import views
from .views import BookListView
urlpatterns = [
path('books/', BookListView.as_view(), name='book_list'),
]

7,进行数据库迁移
打开命令行,进入你的Django项目的根目录。
python manage.py makemigrations
运行python manage.py makemigrations
命令。这个命令会检查你的模型定义,并创建一个迁移文件,这个文件包含了将数据库从当前状态更新到新的模型定义所需的SQL命令。

python manage.py migrate
运行python manage.py migrate
命令。这个命令会执行迁移文件中的SQL命令,更新数据库的结构。

8,访问页面
http://127.0.0.1:8000/app3/books/

访问页面展示
- No books available.
说明数据库表语句创建好了。但是没有表数据
django会自动创建好这些表,

9,插入表数据,再次查看页面
select * from app3_book;
INSERT INTO db1.app3_book
(id,title,author,publication_date)
VALUES(0, 'java入门到弃坑', '余胜军', '2024-06-10');
INSERT INTO db1.app3_book
(id,title,author,publication_date)
VALUES(0, 'python入门到弃坑', '啧啧', '2024-06-11');
INSERT INTO db1.app3_book
(id,title,author,publication_date)
VALUES(0, 'js入门到弃坑', '啧啧3', '2023-06-11');

10,再次刷新页面
http://127.0.0.1:8000/app3/books/
