Django—綜合案例(三)
阿新 • • 發佈:2020-10-29
案例效果如下:
- 開啟 /booktest/顯示書籍列表
- 點選新增,增加一條資料
- 點選刪除,刪除一條資料
- 點選檢視,跳轉英雄資訊介面
1.定義模型類
開啟booktest/models.py檔案,定義模型類如下
from django.db import models
# Create your models here.
# 定義書籍模型類
class BookInfo(models.Model):
btitle = models.CharField(max_length=20) # 書籍名稱
bpub_date = models.DateField() # 釋出日期
bread = models.IntegerField(default=0) # 閱讀量
bcomment = models.IntegerField(default=0) # 評論量
isDelete = models.BooleanField(default=False) # 邏輯刪除
# 定義英雄模型類
class HeroInfo(models.Model):
hname = models.CharField(max_length=20) # 英雄姓名
hgender = models.BooleanField(default=True) # 英雄性別,True為男
hcomment = models.CharField(max_length=200) # 英雄描述資訊
hbook = models.ForeignKey(BookInfo, on_delete=models.DO_NOTHING) # 英雄與書籍關係為一對多
2.遷移
python manage.py makemigrations
python manage.py migrate
表bookinfo結構如下:
注意:預設值並不在資料庫層面生效,而是在django建立物件時生效。
表booktest_heroinfo結構如下:
注意:Django框架會根據關係屬性生成一個關係欄位,並建立外來鍵約束。
3.匯入測試資料
在資料庫命令列中,複製如下語句執行,向booktest_bookinfo和booktest_heroinfo表中插入測試資料:
insert into booktest_bookinfo(id,btitle,bpub_date,bread,bcomment,isDelete) values
(1,'射鵰英雄傳','1980-5-1',12,34,0),
(2,'天龍八部','1986-7-24',36,40,0),
(3,'笑傲江湖','1995-12-24',20,80,0),
(4,'雪山飛狐','1987-11-11',58,24,0);
insert into booktest_heroinfo(hname,hgender,hbook_id,hcomment) values
('郭靖',1,1,'左右互搏'),
('黃蓉',0,1,'打狗棍法'),
('黃藥師',1,1,'彈指神通'),
('歐陽鋒',1,1,'蛤蟆功'),
('梅超風',0,1,'九陰白骨爪'),
('喬峰',1,2,'降龍十八掌'),
('段譽',1,2,'六脈神劍'),
('虛竹',1,2,'天山六陽掌'),
('王語嫣',0,2,'神仙姐姐'),
('令狐沖',1,3,'獨孤九劍'),
('任盈盈',0,3,'彈琴'),
('嶽不群',1,3,'華山劍法'),
('東方不敗',0,3,'葵花寶典'),
('胡斐',1,4,'胡家刀法'),
('苗若蘭',0,4,'黃衣'),
('程靈素',0,4,'醫術'),
('袁紫衣',0,4,'六合拳');
4.定義檢視
開啟booktest/views.py檔案,定義檢視程式碼如下:
import datetime
from django.shortcuts import render, redirect, get_object_or_404
from booktest.models import BookInfo, HeroInfo
from django.http import HttpResponse, Http404
# Create your views here.
# 檢視所有書籍
def index(request):
books = BookInfo.objects.all()
context = {'title': '書籍列表', 'books': books}
return render(request, 'booktest/index.html', context)
# 新增書籍
def create(request):
book = BookInfo()
book.btitle = "流星蝴蝶劍"
book.bpub_date = datetime.date(1995, 12, 30)
book.bread = 0
book.bcomment = 0
book.save()
return redirect("/booktest/")
# 刪除書籍
def delete(request, bid):
# try:
# book = BookInfo.objects.get(id=int(bid))
# book.delete()
# return redirect("/booktest/index")
# except:
# raise Http404("書籍不存在")
book = get_object_or_404(BookInfo, id=int(bid), ) # get_object_or_404() 為快捷函式,不能自定義404顯示資訊
book.delete()
return redirect("/booktest/")
# 檢視英雄資訊
def hero_info(request, bid):
heros = HeroInfo.objects.filter(hbook_id=int(bid))
for hero in heros:
if hero.hgender:
hero.hgender = "男"
else:
hero.hgender = "女"
context = {'title': '英雄資訊', 'heros': heros}
return render(request, "booktest/heroInfo.html", context)
redirect方法是在執行完程式碼後,將介面重定向到index介面,使用時需要import匯入
5.配置url
開啟test1/urls.py檔案,配置url如下:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('booktest/', include('booktest.urls')), # booktest/ 可以為空白
]
在booktest應用下建立urls.py檔案,程式碼如下:
from django.urls import path
from django.urls import re_path
from booktest import views
urlpatterns = [
# ex: /booktest/ # 呼叫index檢視函式
path('', views.index, name='index'),
# ex: /booktest/create # 呼叫create檢視函式
path('create', views.create),
# ex: /booktest/delete/1
# re_path('delete/(\d+)', views.delete), # 在path中使用正則時需要匯入re_path方法
path('delete/<int:bid>', views.delete), # bid為檢視函式的的形參名
path('heroInfo/<int:bid>', views.hero_info)
]
注意:正則分組匹配的值可以當做檢視函式的引數被引用。
6.建立模板
開啟test1/settings.py檔案,配置模板查詢目錄TEMPLATES的DIRS。
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
在templates/booktest/ 目錄下建立index.html和heroInfo.html檔案。
index.html模板程式碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>圖書列表</title>
<style>
body {background-color: #efefef;}
td {text-align: center;}
</style>
</head>
<body>
<h1>{{title}}</h1>
<a href="/booktest/create">新增</a>
<table width="500px">
<tr>
<th>書籍名稱</th>
<th>釋出日期</th>
<th>閱讀量</th>
<th>評論量</th>
<th>操作</th>
</tr>
{%for book in books%}
<tr>
<td>{{book.btitle}}</td>
<td>{{book.bpub_date}}</td>
<td>{{book.bread}}</td>
<td>{{book.bcomment}}</td>
<td>
<a href="/booktest/delete/{{book.id}}">刪除</a>
<a href="/booktest/heroInfo/{{book.id}}">檢視英雄</a>
</td>
</tr>
{%endfor%}
</table>
</body>
</html>
heroInfo.html模板程式碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>英雄資訊</title>
</head>
<body>
<h1>{{title}}</h1>
{% for hero in heros %}
<li> {{ hero.hname }},{{ hero.hgender }},{{ hero.hcomment }}</li>
{% endfor %}
</body>
</html>
7.執行
執行伺服器。
python manage.py runserver
在瀏覽器中檢視http://127.0.0.1:8000/booktest/