web應用框架——使用Mysql數(shù)據(jù)庫完成一個MVT設(shè)計的圖書英雄案例

一.ORM:

在MVC框架中的Model模塊中都包括ORM,對于開發(fā)人員主要帶來了如下好處:

  • 實現(xiàn)了數(shù)據(jù)模型與數(shù)據(jù)庫的解耦,通過簡單的配置就可以輕松更換數(shù)據(jù)庫,而不需要修改代碼。
  • 只需要面向?qū)ο缶幊?,不需要面向?shù)據(jù)庫編寫代碼。
  • 在MVC中Model中定義的類,通過ORM與關(guān)系型數(shù)據(jù)庫中的表對應,對象的屬性體現(xiàn)對象間的關(guān)系,這種關(guān)系也被映射到數(shù)據(jù)表中。

Django框架中ORM示意圖如下:

二.案例創(chuàng)建

1.創(chuàng)建一個django文件

  • workon py_django
  • django-admin startproject test2


    建立

    文件
  • 然后用Pycharm打開這個文件
  • 開始配置編譯環(huán)境(上個文章已經(jīng)教過啦)


    路徑

    環(huán)境

2.更改數(shù)據(jù)庫

  • 找到test2/settings.py 更改數(shù)據(jù)庫


    數(shù)據(jù)庫
  • 修改為MySQL數(shù)據(jù)庫
    將引擎改為mysql,提供連接的主機HOST、端口PORT、數(shù)據(jù)庫名NAME、用戶名USER、密碼PASSWORD。
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test1', #數(shù)據(jù)庫名字,
        'USER': 'root', #數(shù)據(jù)庫登錄用戶名
        'PASSWORD': 'root', #數(shù)據(jù)庫登錄密碼
        'HOST': 'localhost', #數(shù)據(jù)庫所在主機
        'PORT': '3306', #數(shù)據(jù)庫端口
    }
}
修改內(nèi)容
  • 安裝phpsttudy
    百度云安裝包鏈接:https://pan.baidu.com/s/1A_wQuzupBdzozSYUN8kRng
    提取碼:xp8f
    直接點擊exe文件進行下載安裝就可~
    安裝

    啟動數(shù)據(jù)庫

    查看用戶名和密碼
  • 安裝數(shù)據(jù)庫
    百度云數(shù)據(jù)庫安裝包鏈接:https://pan.baidu.com/s/1ESkvrfjyfh2YJDcjxndobA
    提取碼:2rru
    (對于這個數(shù)據(jù)庫安裝完以后,用一個叫PatchNavicat.exe的東西進行破解,這個插件因為百度云敏感所以上傳不了,大家可以百度自行查找)
  • 然后將這個exe文件復制到數(shù)據(jù)庫的路徑下(圖片中有那個exe長的模樣)


    復制文件
  • 雙擊運行這個exe文件


    添加文件

    注冊成功
  • 打開數(shù)據(jù)庫,文件/新建連接


    新建連接

    創(chuàng)建鏈接

    成功鏈接
  • 新建數(shù)據(jù)庫


    新建數(shù)據(jù)庫
  • 添加數(shù)據(jù)庫
    當我們創(chuàng)建完數(shù)據(jù)庫以后,別忘了上方代碼還沒有鏈接數(shù)據(jù)庫


    添加數(shù)據(jù)庫

3.建立應用

  • 首先安裝MySQL的環(huán)境驅(qū)動
    查看是否有MySQL的包


    并沒有PyMySQL的包
  • 安裝
    pip install pymysql


    安裝

    安裝成功
  • 打開test2/init.py文件添加兩行代碼
import pymysql
pymysql.install_as_MySQLdb()
添加代碼
  • 創(chuàng)建一個booktest應用
    python manage.py startapp booktest


    創(chuàng)建應用
  • 將應用注冊到項目中(一定要養(yǎng)成良好習慣哈)
    test2/setting.py文件種修改


    注冊

4.定義模型類

1.模型類被定義在"應用/models.py"文件中,此例中為"booktest/models.py"文件。
2.模型類必須繼承自Model類,位于包django.db.models中。
3.提示:對于重要數(shù)據(jù)使用邏輯刪除。

  • 在booktest/models.py中定義模型類
from django.db import models

# Create your models here.

#定義圖書模型類BookInfo
class BookInfo(models.Model):
    btitle = models.CharField(max_length=20)#圖書名稱
    bpub_date = models.DateField()#發(fā)布日期
    bread = models.IntegerField(default=0)#閱讀量
    bcomment = models.IntegerField(default=0)#評論量
    isDelete = models.BooleanField(default=False)#邏輯刪除

#定義英雄模型類HeroInfo
class HeroInfo(models.Model):
    hname = models.CharField(max_length=20)#英雄姓名
    hgender = models.BooleanField(default=True)#英雄性別
    isDelete = models.BooleanField(default=False)#邏輯刪除
    hcomment = models.CharField(max_length=200)#英雄描述信息
    hbook = models.ForeignKey('BookInfo')#英雄與圖書表的關(guān)系為一對多,所以屬性定義在英雄模型類中
定義模型類
  • 生產(chǎn)遷移文件
    python manage.py makemigrations
    python manage.py migrate


    生成遷移文件

    出現(xiàn)數(shù)據(jù)庫

5.測試數(shù)據(jù)

  • booktest_bookinfo表中插入測試數(shù)據(jù):
insert into booktest_bookinfo(btitle,bpub_date,bread,bcomment,isDelete) values
('射雕英雄傳','1980-5-1',12,34,0),
('天龍八部','1986-7-24',36,40,0),
('笑傲江湖','1995-12-24',20,80,0),
('雪山飛狐','1987-11-11',58,24,0);
  • 向booktest_heroinfo表中插入測試數(shù)據(jù):
insert into booktest_heroinfo(hname,hgender,hbook_id,hcomment,isDelete) values
('郭靖',1,1,'降龍十八掌',0),
('黃蓉',0,1,'打狗棍法',0),
('黃藥師',1,1,'彈指神通',0),
('歐陽鋒',1,1,'蛤蟆功',0),
('梅超風',0,1,'九陰白骨爪',0),
('喬峰',1,2,'降龍十八掌',0),
('段譽',1,2,'六脈神劍',0),
('虛竹',1,2,'天山六陽掌',0),
('王語嫣',0,2,'神仙姐姐',0),
('令狐沖',1,3,'獨孤九劍',0),
('任盈盈',0,3,'彈琴',0),
('岳不群',1,3,'華山劍法',0),
('東方不敗',0,3,'葵花寶典',0),
('胡斐',1,4,'胡家刀法',0),
('苗若蘭',0,4,'黃衣',0),
('程靈素',0,4,'醫(yī)術(shù)',0),
('袁紫衣',0,4,'六合拳',0);
增加數(shù)據(jù)

刷新數(shù)據(jù)庫

刷新數(shù)據(jù)庫

6.定義視圖

  • 創(chuàng)建模板(上一章有講具體操作)


    創(chuàng)建模板
  • 注冊到settings.py中
    'DIRS': [os.path.join(BASE_DIR,'templates')],


    添加語句
  • 創(chuàng)建index.html文件


    index
  • 定義視圖代碼:
    在booktest/views.py文件中編輯:
from django.shortcuts import render
from booktest.models import *
# Create your views here.
#顯示圖書列表
def index(request):
    #查詢所有圖書的信息
    booklist=BookInfo.objects.all()
    return render(request, 'booktest/index.html', {'booklist':booklist})
定義示圖
  • 配置URL
    在test2/urls.py文件中編輯:
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    #引入booktest的url配置
    url(r'^',include('booktest.urls')),
]
配置url
  • 將test2/urls.py文件復制到booktest下,并進行修改
from django.conf.urls import include, url
from django.contrib import admin
from booktest import views
urlpatterns=[
    url(r'^$',views.index),
]
url配置
  • 完善index.html代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圖書列表</title>
</head>
<body>
<h1>圖書列表</h1>
<ul>
    遍歷圖書列表
    {% for book in booklist %}
    <li>
        <a href="">{{ book.btitle }}</a>
    </li>
    {% endfor %}
</ul>
</body>
</html>
  • 啟動程序
    python manage.py runserver


    運行成功
  • 在瀏覽器中輸入網(wǎng)址:http://127.0.0.1:8000/


    出現(xiàn)圖書列表
  • 修改一下index.html中的代碼(查看閱讀量)


    修改代碼

    刷新一下就會出現(xiàn)閱讀量啦~


    顯示閱讀量

7.編寫第二個示圖功能

  • 創(chuàng)建一個detail.html文件


    detail.html
<html>
<head>
    <title>詳細頁</title>
</head>
<body>
{#輸出圖書標題#}
<h1>{{book.btitle}}</h1>
<ul>
    {#通過關(guān)系找到本圖書的所有英雄,并遍歷#}
    {%for hero in heros%}
    {#輸出英雄的姓名及描述#}
    <li>{{hero.hname}}---{{hero.hcomment}}</li>
    {%endfor%}
</ul>
</body>
</html>
detail代碼
  • 修改booktest/views.py文件
#詳細頁,接收圖書的編號,根據(jù)編號查詢,再通過關(guān)系找到本圖書的所有英雄并展示
def detail(reqeust, bid):
    #根據(jù)圖書編號對應圖書
    book = BookInfo.objects.get(id=int(bid))
    #查找book圖書中的所有英雄信息
    heros = book.heroinfo_set.all()
    #將圖書信息傳遞到模板中,然后渲染模板
    return render(reqeust, 'booktest/detail.html', {'book':book,'heros':heros})
修改代碼
  • 打開index.html文件


    填寫鏈接
  • 配置url
    打開booktest/urls.py文件

from django.conf.urls import url
#引入視圖模塊
from booktest import views
urlpatterns = [
    #配置首頁url
    url(r'^$', views.index),
    #配置詳細頁url,\d+表示多個數(shù)字,小括號用于取值,建議復習下正則表達式
    url(r'^(\d+)/$',views.detail),
]
定義url
  • 刷新界面


    成功

8.增加功能

修改顯示形式
  • 新增加一個index2.html,里面的代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圖書列表</title>
</head>
<body>
<h1>圖書列表</h1>
<a href="">創(chuàng)建一本書</a>
<ul>
    {# 遍歷圖書列表 #}
    {% for book in list %}
    <li>
        {{ book.btitle }}---><a href="/delate">刪除</a>
    </li>
    {% endfor %}
</ul>
</body>
</html>
代碼
  • 修改view.py文件代碼:
def index2(request):
    #查詢所有圖書的信息
    list=BookInfo.objects.all()
    return render(request, 'booktest/index2.html', {'list':list})
修改代碼
  • 配置urls.py
    url(r'^list$',views.index2),


    配置
  • 輸入網(wǎng)址:http://127.0.0.1:8000/list
    成功界面
  • 修改index2.html代碼:


    修改代碼
  • 修改view.py代碼:
from django.shortcuts import render,redirect
from booktest.models import *
from datetime import date
# Create your views here.
#顯示圖書列表
def index(request):
    #查詢所有圖書的信息
    booklist=BookInfo.objects.all()
    return render(request, 'booktest/index.html', {'booklist':booklist})


#詳細頁,接收圖書的編號,根據(jù)編號查詢,再通過關(guān)系找到本圖書的所有英雄并展示
def detail(reqeust, bid):
    #根據(jù)圖書編號對應圖書
    book = BookInfo.objects.get(id=int(bid))
    #查找book圖書中的所有英雄信息
    heros = book.heroinfo_set.all()
    #將圖書信息傳遞到模板中,然后渲染模板
    return render(reqeust, 'booktest/detail.html', {'book':book,'heros':heros})

def index2(request):
    #查詢所有圖書的信息
    list=BookInfo.objects.all()
    return render(request, 'booktest/index2.html', {'list':list})

#創(chuàng)建新圖書
def create(request):
    book=BookInfo()
    book.btitle = '天涯明月刀'
    book.bpub_date = date(1995,12,30)
    book.save()
    #轉(zhuǎn)向到首頁,上面信息被數(shù)據(jù)庫保存
    return redirect('/list')
需要注意的地方

9刪除功能

  • 修改index2.html文件


    修改
  • 修改views.py文件
#邏輯刪除指定編號的圖書
def delete(request,id):
    book=BookInfo.objects.get(id=int(id))
    book.delete()
    #轉(zhuǎn)向到list
    return redirect('/list')
添加代碼如下

(此文章僅作為個人學習筆記使用,如有錯誤歡迎指正~)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容