第六模塊:WEB框架開發 第1章·Django框架開發1~50

  • 01-Django基礎介紹
  • 02-Web應用程序1
  • 03-Web應用程序2
  • 04-http請求協議1
  • 05-http請求協議2
  • 06-http協議之響應協議
  • 07-wsgire模塊1
  • 08-wsgire模塊2
  • 09-DIY一個Web框架1
  • 10-DIY一個Web框架2
  • 11-DIY一個Web框架3
  • 12-框架的簡單使用
  • 13-擴展框架關於數據庫的操做
  • 14-Django簡介
  • 15-Django的下載與基本命令
  • 16-Django簡單實例
  • 17-靜態文件配置1
  • 18-靜態文件配置2
  • 19-路由控制之「簡單配置」
  • 20-路由控制之「有名分組」
  • 21-路由控制之「分發」
  • 22-路由控制之登陸驗證示例
  • 23-路由控制之反向解析1
  • 24-流程控制之反向解析2
  • 25-路由控制之名稱空間1
  • 26-路由控制之名稱空間2
  • 27-url控制器之path方法
  • 28-path的自定義轉換器
  • 29-url控制總結
  • 30-視圖層之請求對象
  • 31-視圖響應對象
  • 32-模版語法之變量
  • 33-過濾器
  • 34-模版語法之標籤
  • 35-模版語法之自定義標籤與過濾器
  • 36-模版語法之繼承
  • 37-ORM簡介
  • 38-單表操做之生成表模型
  • 39-單表操做之添加記錄
  • 40-單表操做之查詢API-1
  • 41-單表操做之查詢API-2
  • 42-單表操做之查詢API-3
  • 43-單表操做之模糊查詢
  • 44-單表查詢之刪除與修改操做
  • 45-單表操做章節做業
  • 46-單表操做章節做業講解
  • 47-圖書管理系統之添加頁面
  • 48-圖書管理系統之查看書籍
  • 49-圖書管理系統之刪除數據
  • 50-圖書管理系統之編輯功能

01-Django基礎介紹

一、什麼是Django?

  Python中最強大的Web開發框架;

二、Web框架是什麼?(Web應用框架);

  什麼是Web應用?css

  欲知後事如何請聽下回分解;html

三、客戶端和服務端;

  • 發送請求的一端;
  • 接受請求並做出響應的一端;

四、請求過程和相應過程;

  • 向服務端發送字符串的過程;
  • 解析來自客戶端的數據,並返回數據的過程;

五、開發的是服務端;

  Server.py;前端

六、成熟的客戶端;

  • Chrome;
  • Firefox;
  • IE;
  • Safari;
  • Opera;
  • 其餘第三方瀏覽器,如360極速瀏覽器、QQ瀏覽器、搜狗極速瀏覽器;

02-Web應用程序1

一、開發簡單的server.py;

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 12:05
import socket

sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5)

#進入通訊循環;
while True:
    print("JDServer is waiting....")
    conn,addr = sock.accept()
    data = conn.recv(1024)
    print("data",data)
    #conn.send(b"Hello LuffyCity!")
    conn.send(b"HTTP/1.1 200 OK\r\n\r\nHello LuffyCity!")
    conn.close()

03-Web應用程序2

一、server.py;

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 12:05
import socket

sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5)

#進入通訊循環;
while True:
    print("JDServer is waiting....")
    conn,addr = sock.accept()
    data = conn.recv(1024)
    print("data",data)
    #conn.send(b"Hello LuffyCity!")
    with open("index.html","rb") as f:
        data = f.read()
    conn.send(("HTTP/1.1 200 OK\r\n\r\n%s"%data).encode("gbk"))
    conn.close()

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>03-Web應用程序02</title>
    <style type="text/css">

    </style>
</head>
<body>
<h1>Hello LuffyCity!</h1>
<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534231128705&di=067e25afed9b53931f6cfc95485c880a&imgtype=0&src=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201609%2F12%2F20160912220442_yQCLi.jpeg'>
<a href="http://www.luffycity.com">路飛學城</a>
</body>
</html>
index.html

04-http請求協議1

一、HTTP協議初識;

  1)HTTP協議是Hyper Text Transfer Protocol(超文本傳輸協議)的縮寫,是用於萬維網(WWW:World Wide Web )服務器與本地瀏覽器之間傳輸超文本的傳送協議;java

  2)HTTP是一個屬於應用層的面向對象的協議,因爲其簡捷、快速的方式,適用於分佈式超媒體信息系統,它於1990年提出,通過幾年的使用與發展,獲得不斷地完善和擴展,HTTP協議工做於客戶端-服務端架構之上;python

  3)瀏覽器做爲HTTP客戶端經過URL向HTTP服務端即WEB服務器發送全部請求,Web服務器根據接收到的請求後,向客戶端發送響應信息;mysql

二、HTTP協議是基於TCP/IP協議之上的「應用層協議」;

三、HTTP協議是基於「請求<--->響應」模式;

  HTTP協議規定,請求從客戶端發出,最後服務器端響應該請求並返回。換句話說,確定是先從客戶端開始創建通訊的,服務器端在沒有接收到請求以前不會發送響應;jquery

四、HTTP協議「無狀態保存」;

  HTTP是一種不保存狀態,即無狀態(stateless)協議。HTTP協議自身不對請求和響應之間的通訊狀態進行保存。也就是說在HTTP這個級別,協議對於發送過的請求或響應都不作持久化處理;nginx

五、HTTP協議「無鏈接」;

  無鏈接的含義是限制每次鏈接只處理一個請求。服務器處理完客戶的請求,並收到客戶的應答後,即斷開鏈接。採用這種方式能夠節省傳輸時間;git

 

六、請求格式;

七、請求方式:GET和POST請求;

  • GET請求提交的數據會放在URL以後,以?分割URL的傳輸的數據,參數之間使用&相鏈接,好比?name=cuixiaozhao&age=26,POST方法是把提交的數據放在HTTP包的「請求體」中;
  • GET提交的數據大小有限制(由於瀏覽器對URL的長度有限制),而POST方法提交的數據沒有限制;
  • GET與POST請求在服務端獲取請求數據方式不一樣;

操做日誌:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:04

import socket

sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5)

#進入通訊循環;
while 1:
    print("JDServer is waiting123....")
    conn,addr = sock.accept()
    data = conn.recv(1024)
    print("data",data)
    #conn.send(b"Hello LuffyCity!")
    #讀取html文件;
    with open("index.html","rb") as f:
        data = f.read()
    #conn.send(b"HTTP/1.1 200 OK\r\n\r\n%s"%data)
    conn.send((b"HTTP/1.1 200 OK\r\n\r\n%s"%data))
    conn.close()
'''
請求首行:
請求頭:
請求頭:
請求頭:
請求頭:
請求頭:
請求頭:
請求體:(name=cuixiaozhao&age=26),注意只有POST請求才有"請求體"!

data b'GET / HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Cache-Control: max-age=0\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq\r\n
\r\n'
JDServer is waiting123....
'''

"""

data b'GET /tqtl?name=cuixiaozhao&age=26 HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Upgrade-Insecure-Requests: 1\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq\r\n
\r\n'
JDServer is waiting123....
"""

05-http請求協議2

一、http請求協議之post請求;

操做日誌:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:04

import socket

sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5)

#進入通訊循環;
while 1:
    print("JDServer is waiting123....")
    conn,addr = sock.accept()
    data = conn.recv(1024)
    print("data",data)
    #讀取html文件;
    with open("login.html","rb") as f:
        data = f.read()
    conn.send((b"HTTP/1.1 200 OK\r\n\r\n%s"%data))
    conn.close()
"""
data b'POST / HTTP/1.1\r\n
Host: 127.0.0.1:8800\r\n
Connection: keep-alive\r\n
Content-Length: 36\r\n
Cache-Control: max-age=0\r\n
Origin: http://127.0.0.1:8800\r\n
Upgrade-Insecure-Requests: 1\r\n
Content-Type: application/x-www-form-urlencoded\r\n
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36\r\n
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\r\n
Referer: http://127.0.0.1:8800/\r\n
Accept-Encoding: gzip, deflate, br\r\n
Accept-Language: zh-CN,zh;q=0.9\r\n
Cookie: csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq\r\n
\r\nusername=cuixiaozhao&password=Ab123.'
JDServer is waiting123....
"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>03-Web應用程序02</title>
    <style type="text/css">

    </style>
</head>
<body>
<form action="http://127.0.0.1:8800" method="post">
    用戶名:<input type="text" name="username" >
    密碼:<input type="password" name="password" >
    <input type="submit"></input>
</form>
</body>
</html>

06-http協議之響應協議

一、get與post的使用場景;

  • get即獲取的意思,好比對數據庫的查詢操做;
  • post即提交的意思,好比增、刪和改等操做;

另外補充:web

  • GET方式提交數據,會帶來安全問題,好比一個登陸頁面,經過GET方式提交數據時,用戶名和密碼將出如今URL上,若是頁面能夠被緩存或者其餘人能夠訪問這臺機器,就能夠從歷史記錄得到該用戶的帳號和密碼;

二、http協議之響應協議初識;

三、響應的狀態碼;

  狀態碼指的是當客戶端向服務器端發送請求時, 返回的請求結果,藉助狀態碼,用戶能夠知道服務器端是正常處理了請求,仍是出現異常了 。

操做日誌:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:44
import socket

sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5)

#進入通訊循環;
while 1:
    print("JDServer is waiting123....")
    conn,addr = sock.accept()
    data = conn.recv(1024)
    print("data",data)
    #讀取html文件;
    with open("login.html","rb") as f:
        data = f.read()
    conn.send((b"HTTP/1.1 200 OK\r\nContent-Type:text\r\n\r\n%s"%data))
    conn.close()

07-wsgire模塊1

一、Web應用;

  1)Web應用程序是一種能夠經過Web訪問的應用程序,程序的最大好處是用戶很容易訪問應用程序,用戶只須要有瀏覽器便可,不須要再安裝其餘軟件;

  2)應用程序有兩種模式C/S、B/S。C/S是客戶端/服務器端程序,也就是說這類程序通常獨立運行。而B/S就是瀏覽器/服務器端應用程序,這類應用程序通常藉助谷歌,火狐等瀏覽器來運行;

  3)Web應用程序通常是B/S模式。Web應用程序首先是「應用程序」,和用標準的程序語言,如java,python等編寫出來的程序沒有什麼本質上的不一樣。

  4)  在網絡編程的意義下,瀏覽器是一個socket客戶端,服務器是一個socket服務端;

二、Web框架;

  Web框架(Web framework)是一種開發框架,用來支持動態網站、網絡應用和網絡服務的開發。這大多數的Web框架提供了一套開發和部署網站的方式,也爲Web行爲提供了一套通用的方法;

  Web框架已經實現了不少功能,開發人員使用框架提供的方法而且完成本身的業務邏輯,就能快速開發Web應用了。瀏覽器和服務器的是基於HTTP協議進行通訊的。也能夠說Web框架就是在以上十幾行代碼基礎張擴展出來的,有不少簡單方便使用的方法,大大提升了開發的效率;

三、wsgiref模塊初識;

  最簡單的Web應用就是先把HTML用文件保存好,用一個現成的HTTP服務器軟件,接收用戶請求,從文件中讀取HTML,返回;

  若是要動態生成HTML,就須要把上述步驟本身來實現。不過,接受HTTP請求、解析HTTP請求、發送HTTP響應都是苦力活,若是咱們本身來寫這些底層代碼,還沒開始寫動態HTML呢,就得花個把月去讀HTTP規範;

  正確的作法是底層代碼由專門的服務器軟件實現,咱們用Python專一於生成HTML文檔。由於咱們不但願接觸到TCP鏈接、HTTP原始請求和響應格式,因此,須要一個統一的接口協議來實現這樣的服務器軟件,讓咱們專心用Python編寫Web業務。這個接口就是WSGI:Web Server Gateway Interface,而wsgiref模塊就是python基於wsgi協議開發的服務模塊;

操做日誌:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 17:44
import socket

sock = socket.socket()
sock.bind(("127.0.0.1",8800))
sock.listen(5)

#進入通訊循環;
while 1:
    print("JDServer is waiting123....")
    conn,addr = sock.accept()
    data = conn.recv(1024)#------------------dict/obj  d={"path":"/login"}
    print("data",data)
    #讀取html文件;
    with open("login.html","rb") as f:
        data = f.read()
    conn.send((b"HTTP/1.1 200 OK\r\nContent-Type:text\r\n\r\n%s"%data))
    conn.close()

'''
一、按照HTTP請求協議解析數據;
#專一於Web的業務開發;
    path = d.get("path")
    if path == "/login":
        return login.html
二、按照HTTP響應協議封裝數據;
'''

08-wsgire模塊2

一、Web框架代碼演示:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 20:52
from wsgiref.simple_server import make_server


print("is starting")
def application(environ, start_response):
    #按照http協議解析數據:environ;
    #按照http協議進行組裝數據:start_response;
    print(environ)
    print(type(environ))
    #當前的請求路徑;
    path = environ.get("PATH_INFO")
    start_response('200 OK',[])
    if path == "/login":
        with open("login.html","r") as f:
            data = f.read()
     return [data]
elif path == "/index": with open("index.html","r") as f: data = f.read()
     return [data]
# start_response('200 OK',[]) return [b"<h1>Hello Web</h1>"] # 已經封裝了socket模塊的前三步; httpd = make_server("",8800,application)#封裝了socket; #等待用戶鏈接:conn,addr = sock.accept() httpd.serve_forever()#application(environ,start_response) """ {'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': 'C:\\Users\\TQTL911\\AppData\\Roaming', 'CLASSPATH': '.;C:\\Program Files\\Java\\jdk1.7.0_80\\lib;C:\\Program Files\\Java\\jdk1.7.0_80\\lib\\tools.jar', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'COMMONPROGRAMFILES(X86)': 'C:\\Program Files (x86)\\Common Files', 'COMMONPROGRAMW6432': 'C:\\Program Files\\Common Files', 'COMPUTERNAME': 'DESKTOP-U8JDGPP', 'COMSPEC': 'C:\\Windows\\system32\\cmd.exe', 'DRIVERDATA': 'C:\\Windows\\System32\\Drivers\\DriverData', 'FPS_BROWSER_APP_PROFILE_STRING': 'Internet Explorer', 'FPS_BROWSER_USER_PROFILE_STRING': 'Default', 'HOMEDRIVE': 'C:', 'HOMEPATH': '\\Users\\TQTL911', 'JAVA_HOME': 'C:\\Program Files\\Java\\jdk1.7.0_80', 'LOCALAPPDATA': 'C:\\Users\\TQTL911\\AppData\\Local', 'LOGONSERVER': '\\\\DESKTOP-U8JDGPP', 'NUMBER_OF_PROCESSORS': '8', 'OS': 'Windows_NT', 'PATH': 'C:\\Program Files\\Python36\\;C:\\Program Files\\Python36\\Scripts\\;C:\\Program Files\\Python27\\;C:\\Program Files\\Python27\\Scripts;D:\\Program\\Anaconda3;D:\\Program\\Anaconda3\\Library\\mingw-w64\\bin;D:\\Program\\Anaconda3\\Library\\usr\\bin;D:\\Program\\Anaconda3\\Library\\bin;D:\\Program\\Anaconda3\\Scripts;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files\\MySQL\\MySQL Utilities 1.6\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin;C:\\Program Files\\Java\\jdk1.7.0_80\\bin;C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\;D:\\Program\\Redis3.2.10\\;D:\\Program\\Tesseract-OCR;;D:\\Program\\WinMerge;C:\\Users\\TQTL911\\AppData\\Local\\Microsoft\\WindowsApps;C:\\Users\\TQTL911\\PycharmProjects\\Web開發\\venv\\Scripts', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.PYW', 'PROCESSOR_ARCHITECTURE': 'AMD64', 'PROCESSOR_IDENTIFIER': 'Intel64 Family 6 Model 94 Stepping 3, GenuineIntel', 'PROCESSOR_LEVEL': '6', 'PROCESSOR_REVISION': '5e03', 'PROGRAMDATA': 'C:\\ProgramData', 'PROGRAMFILES': 'C:\\Program Files', 'PROGRAMFILES(X86)': 'C:\\Program Files (x86)', 'PROGRAMW6432': 'C:\\Program Files', 'PROMPT': '(venv) $P$G', 'PSMODULEPATH': 'C:\\Program Files\\WindowsPowerShell\\Modules;C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules', 'PUBLIC': 'C:\\Users\\Public', 'PYCHARM_HOSTED': '1', 'PYCHARM_MATPLOTLIB_PORT': '50456', 'PYTHONIOENCODING': 'UTF-8', 'PYTHONPATH': 'D:\\Program\\PyCharm 2018.1.4\\helpers\\pycharm_matplotlib_backend;C:\\Users\\TQTL911\\PycharmProjects\\Web開發', 'PYTHONUNBUFFERED': '1', 'SESSIONNAME': 'Console', 'SYSTEMDRIVE': 'C:', 'SYSTEMROOT': 'C:\\Windows', 'TEMP': 'C:\\Users\\TQTL911\\AppData\\Local\\Temp', 'TESSDATA_PREFIX': 'D:\\Program\\Tesseract-OCR\\tessdata', 'TMP': 'C:\\Users\\TQTL911\\AppData\\Local\\Temp', 'USERDOMAIN': 'DESKTOP-U8JDGPP', 'USERDOMAIN_ROAMINGPROFILE': 'DESKTOP-U8JDGPP', 'USERNAME': 'TQTL911', 'USERPROFILE': 'C:\\Users\\TQTL911', 'VIRTUAL_ENV': 'C:\\Users\\TQTL911\\PycharmProjects\\Web寮�鍙憖venv', 'VS140COMNTOOLS': 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\', 'WINDIR': 'C:\\Windows', '_OLD_VIRTUAL_PATH': 'C:\\Program Files\\Python36\\;C:\\Program Files\\Python36\\Scripts\\;C:\\Program Files\\Python27\\;C:\\Program Files\\Python27\\Scripts;D:\\Program\\Anaconda3;D:\\Program\\Anaconda3\\Library\\mingw-w64\\bin;D:\\Program\\Anaconda3\\Library\\usr\\bin;D:\\Program\\Anaconda3\\Library\\bin;D:\\Program\\Anaconda3\\Scripts;C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\Windows\\System32\\OpenSSH\\;C:\\Program Files\\MySQL\\MySQL Utilities 1.6\\;C:\\Program Files (x86)\\NVIDIA Corporation\\PhysX\\Common;C:\\Program Files\\MySQL\\MySQL Server 5.7\\bin;C:\\Program Files\\Java\\jdk1.7.0_80\\bin;C:\\Program Files (x86)\\Windows Kits\\8.1\\Windows Performance Toolkit\\;D:\\Program\\Redis3.2.10\\;D:\\Program\\Tesseract-OCR;;D:\\Program\\WinMerge;C:\\Users\\TQTL911\\AppData\\Local\\Microsoft\\WindowsApps', '_OLD_VIRTUAL_PROMPT': '$P$G', 'SERVER_NAME': 'DESKTOP-U8JDGPP', 'GATEWAY_INTERFACE': 'CGI/1.1', 'SERVER_PORT': '18080', 'REMOTE_HOST': '', 'CONTENT_LENGTH': '', 'SCRIPT_NAME': '', 'SERVER_PROTOCOL': 'HTTP/1.1', 'SERVER_SOFTWARE': 'WSGIServer/0.2', 'REQUEST_METHOD': 'GET', 'PATH_INFO': '/2321', 'QUERY_STRING': '', 'REMOTE_ADDR': '127.0.0.1', 'CONTENT_TYPE': 'text/plain', 'HTTP_HOST': '127.0.0.1:18080', 'HTTP_CONNECTION': 'keep-alive', 'HTTP_UPGRADE_INSECURE_REQUESTS': '1', 'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.12 Safari/537.36', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate, br', 'HTTP_ACCEPT_LANGUAGE': 'zh-CN,zh;q=0.9', 'HTTP_COOKIE': 'csrftoken=V87q4DAWGWiZjGlroQ26elLbUtzrzIaxPS3zy6t8Hn71BCTQBTXM4UVqoMNB4sf8; sessionid=7b47t1sqsplymr83a167lt1c6y2pa0kq', 'wsgi.input': <_io.BufferedReader name=436>, 'wsgi.errors': <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, 'wsgi.version': (1, 0), 'wsgi.run_once': False, 'wsgi.url_scheme': 'http', 'wsgi.multithread': True, 'wsgi.multiprocess': False, 'wsgi.file_wrapper': <class 'wsgiref.util.FileWrapper'>} <class 'dict'> """

09-DIY一個Web框架

 一、DIY一個Web框架01;

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 22:11
from wsgiref.simple_server import make_server

def application(environ, start_response):
    start_response('200 OK',[('Content-Type', 'text/html')])
    print('PATH',environ.get('PATH_INFO'))
    path = environ.get('PATH_INFO')
    if path == "/favicon.ico":
        with open("favicon.ico","rb") as f:
            data = f.read()
        return [data]
    return [b'<h1>Hello,World!</h1>']

httpd = make_server('', 8080, application)
print('Server HTTP on port 8080')
#開始監聽HTTP請求;
httpd.serve_forever()

10-DIY一個Web框架2

一、DiY一個Web框架2;

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/14 22:11
from wsgiref.simple_server import make_server

def login(environ):
    with open("login.html","rb")as f:
        data = f.read()
    return data
def index(environ):
    with open("index.html","rb")as f:
        data = f.read()
    return data
def fav(environ):
    with open("favicon.ico","rb")as f:
        data = f.read()
    return data
def reg(environ):
    with open("reg.html","rb")as f:
        data = f.read()
    return data

def application(environ, start_response):
    start_response('200 OK',[('Content-Type', 'text/html'),("Charset","utf8")])
    print('PATH',environ.get('PATH_INFO'))
    path = environ.get('PATH_INFO')
#     #方案1:
#     if path == "/favicon.ico":
#         with open("favicon.ico","rb") as f:
#             data = f.read()
#         return [data]
#     elif path =="/login":
#         with open("login.html","rb")as f:
#             data = f.read()
#         return [data]
#     elif path =="/index":
#         with open("index.html","rb")as f:
#             data = f.read()
#         return [data]
#     elif path =="/reg":
#         with open("reg.html","rb")as f:
#             data = f.read()
#         return [data]
# #方案2:
    url_patterns = [
        ("/login",login),
        ("/index",index),
        ("/favicon.ico",fav),
        ("/reg",reg)
    ]

    func = None
    for item in url_patterns:
        if path == item[0]:
            func = item[1]
            break
    if func:
        return [func(environ)]
    else:
        return [b"404"]

httpd = make_server("", 19988, application)
print('Server HTTP on port 19988')
#開始監聽HTTP請求;
httpd.serve_forever()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>03-Web應用程序02</title>
    <style type="text/css">

    </style>
</head>
<body>
<h1>Hello LuffyCity!</h1>
<img src='https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1534231128705&di=067e25afed9b53931f6cfc95485c880a&imgtype=0&src=http%3A%2F%2Fimg5.duitang.com%2Fuploads%2Fitem%2F201609%2F12%2F20160912220442_yQCLi.jpeg'>
<a href="http://www.luffycity.com">路飛學城</a>
</body>
</html>
index
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>03-Web應用程序02</title>
    <style type="text/css">

    </style>
</head>
<body>
<form action="http://127.0.0.1:19988" method="post">
    用戶名:<input type="text" name="username" >
    密碼:<input type="password" name="password" >
    <input type="submit"></input>
</form>
</body>
</html>
login
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h4>註冊頁面</h4>

</body>
</html>
reg

11-DIY一個Web框架3

一、DIY一個Web框架3;

  程序解耦合操做,提升層次結構。

12-框架的簡單使用 

一、在本身或者其餘人寫好的基礎(重複複用的代碼)代碼之上,進行新功能拓展的packages就叫作Web框架;

二、Web框架是用來進行Web應用開發的一個軟件架構,主要用於動態網絡開發,開發者在基於Web框架實現本身的業務邏輯。Web框架實現了不少功能,爲實現業務邏輯提供了一套通用方法;

13-擴展框架關於數據庫的操做

一、自行開發的Web框架的目錄結構;

二、代碼目錄;

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:31
from wsgiref.simple_server import make_server

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html'),('Charset','utf8')])
    print("PATH",environ.get("PATH_INFO"))
    path = environ.get("PATH_INFO")

    from urls import url_patterns
    func = None

    for item in url_patterns:
        if path == item[0]:
            func = item[1]
            break
    if func:
        return [func(environ)]
    else:
        return [b'404 not find pages']


httpd = make_server("",9988, application)

#開始監聽HTTP請求;
httpd.serve_forever()
main.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:34
#在數據庫中,生成用戶表;

import pymysql
#鏈接MySQL數據庫;
conn=pymysql.connect(host='localhost',user='root',password='Tqtl911!@#)^',database='django',charset='utf8')
#建立遊標;
cursor=conn.cursor() #執行完畢返回的結果集默認以元組顯示

#執行sql語句;
sql='''
create table userinfo(
id int primary  key,
name varchar (32),
password varchar (32)
)
'''
print(sql)
res=cursor.execute(sql) #執行sql語句,返回sql查詢成功的記錄數目
print(res)

#提交
conn.commit()
#關閉指針對象
cursor.close()
#關閉鏈接對象
conn.close()


"""
main.py:啓動文件,封裝了socket;
獨立開發的Web框架總結:
一、urls.py:路徑與視圖函數的對應關係,------url控制器;
二、views.py:整個視圖函數,固定有一個形式參數-environ,------視圖函數;
三、templates目錄:html文件, ---------模板部分;
四、models:在項目啓動前,在數據庫中建立表結構,-------與數據庫相關;
"""
models.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:33

from views import *

url_patterns = [
    ('/login',login),
    ('/index',index),
    ('/favicon.ico',fav),
    ('/timer',timer),
    ('/auth',auth),
    ('/reg',reg),
]
urls.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 10:33
def login(environ):
    with open("templates/login.html","rb") as f:
        data =f.read()
    return data

from urllib.parse import  parse_qs

def index(environ):
    with open("templates/index.html","rb") as f:
        data = f.read()
    return data

def fav(environ):
    with open("templates/favicon.ico","rb") as f:
        data = f.read()
    return data

def reg(environ):
    with open("templates/reg.html","rb") as f:
        data = f.read()
    return data

def timer(environ):
    import datetime
    now = datetime.datetime.now().strftime("%y-%m-%d %X")
    return now.encode("utf8")


def auth(request):
    try:
        request_body_size = int(request.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0

    request_body = request['wsgi.input'].read(request_body_size)
    data = parse_qs(request_body)

    user = data.get(b"user")[0].decode("utf8")
    pwd = data.get(b"pwd")[0].decode("utf8")

#鏈接MySQL數據庫;
    import pymysql
    conn = pymysql.connect(host = "127.0.0.1",port = 3306,user = "root",passwd = "Tqtl911!@#)^",db = "django")
    #建立遊標;
    cursor = conn.cursor()
    SQL = "select * from userinfo where name = '%s' and password = '%s' "%(user,pwd)
    cursor.execute(SQL)
    if cursor.fetchone():
        with open("templates/backend.html","rb") as f:
            data = f.read()
            data = data.decode("utf8")
            return data.encode("utf8")
    else:
        return b"user or pwd is wrong."
views.py

三、小結:

"""
main.py:啓動文件,封裝了socket;
獨立開發的Web框架總結:
一、urls.py:路徑與視圖函數的對應關係,------url控制器;
二、views.py:整個視圖函數,固定有一個形式參數-environ,------視圖函數;
三、templates目錄:html文件, ---------模板部分;
四、models:在項目啓動前,在數據庫中建立表結構,-------與數據庫相關;
"""

14-Django簡介

一、什麼是MVC模型?

  Web服務器開發領域裏著名的MVC模式,所謂MVC就是把Web應用分爲模型(Mondel),控制器(Controller)和視圖(View)三層,他們之間以一種插件式的、鬆耦合的方式鏈接在一塊兒,模型負責業務對象與數據庫的映射(ORM),視圖負責與用戶的交互(頁面),控制器接受用戶的輸入調用模型和視圖完成用戶的請求,其示意圖以下所示:

 

二、什麼是MTV模型?

  Django的MTV模式本質上和MVC是同樣的,也是爲了各組件間保持鬆耦合關係,只是定義上有些許不一樣,Django的MTV分別是值:

  • M表明模型(Model):負責業務對象和數據庫的關係映射(ORM);
  • T表明模板(Template):負責如何把頁面展現給用戶(html);
  • V表明視圖(View):負責業務邏輯,並在適當時候調用Model和Template;

  除了以上三層以外,還須要一個URL分發器,它的做用是將一個個URL的頁面請求分發給不一樣的View處理,View再調用相應的Model和Template,MTV的響應模式以下所示:

  通常是用戶經過瀏覽器向咱們的服務器發起一個請求(request),這個請求回去訪問視圖函數,(若是不涉及到數據調用,那麼這個時候視圖函數返回一個模板也就是一個網頁給用戶),視圖函數調用模型,模型去數據庫查找數據,而後逐級返回,視圖函數把返回的數據填充到模板中空格中,最後返回網頁給用戶。

15-Django的下載與基本命令

 

一、下載並安裝Django;

pip3 install django==2.0.1

1)  Django官網:https://www.djangoproject.com/

2)  亦可以使用編譯安裝(不推薦);

二、建立一個Django project——mysite;

django-admin startproject mysite(mysite爲項目名稱,自行自定義!)

三、在項目下建立應用——blog、app01(app名稱自行定義);

python manage.py startapp blog
python manage.py startapp app01

四、啓動Django項目;

 相對路徑:先進入django項目的主目錄再進行啓動;

python manage.py runserver 19939(能夠不指定端口,默認爲8000,建議使用大於10000的端口號)

五、查看Django項目的啓動效果;

http://127.0.0.1:19939

 操做日誌:

Microsoft Windows [版本 10.0.17134.1]
(c) 2018 Microsoft Corporation。保留全部權利。

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>dir
 驅動器 C 中的卷沒有標籤。
 卷的序列號是 B2D2-AA19

 C:\Users\TQTL911\PycharmProjects\LFXC2018 的目錄

2018/08/11  12:45    <DIR>          .
2018/08/11  12:45    <DIR>          ..
2018/08/15  15:06    <DIR>          .idea
2018/07/29  15:52    <DIR>          data
2018/07/16  13:49    <DIR>          homework
2018/08/14  09:59    <DIR>          myblog
2018/07/18  21:39    <DIR>          mysite
2018/07/29  16:07    <DIR>          Python3網絡爬蟲實戰
2018/07/29  15:51    <DIR>          venv
2018/06/30  17:51    <DIR>          第1模塊開發基礎
2018/07/03  16:16    <DIR>          第2模塊函數編程
2018/07/14  16:11    <DIR>          第3模塊面向對象&網絡編程基礎
2018/07/27  18:06    <DIR>          第4模塊網絡編程進階&數據庫開發
2018/08/01  11:07    <DIR>          第5模塊WEB開發基礎
2018/07/17  17:37    <DIR>          考覈目錄
               0 個文件              0 字節
              15 個目錄 86,502,342,656 可用字節

(venv) C:\Users\TQTL911\PycharmProjects\LFXC2018>cd ..

(venv) C:\Users\TQTL911\PycharmProjects>ll
'll' 不是內部或外部命令,也不是可運行的程序
或批處理文件。

(venv) C:\Users\TQTL911\PycharmProjects>dir
 驅動器 C 中的卷沒有標籤。
 卷的序列號是 B2D2-AA19

 C:\Users\TQTL911\PycharmProjects 的目錄

2018/08/14  12:05    <DIR>          .
2018/08/14  12:05    <DIR>          ..
2018/08/11  12:45    <DIR>          LFXC2018
2018/08/15  14:46    <DIR>          Web開發
               0 個文件              0 字節
               4 個目錄 86,502,252,544 可用字節

(venv) C:\Users\TQTL911\PycharmProjects>cd We
系統找不到指定的路徑。

(venv) C:\Users\TQTL911\PycharmProjects>cd Web開發

(venv) C:\Users\TQTL911\PycharmProjects\Web開發>django-admin.py startproject tqtl
Traceback (most recent call last):
  File "C:\Users\TQTL911\PycharmProjects\LFXC2018\venv\Scripts\django-admin.py", line 2, in <module>
    from django.core import management
ImportError: No module named django.core

(venv) C:\Users\TQTL911\PycharmProjects\Web開發>django-admin startproject tqtl

(venv) C:\Users\TQTL911\PycharmProjects\Web開發>django-admin startproject tqtl911

(venv) C:\Users\TQTL911\PycharmProjects\Web開發>django-admin startproject mysite

(venv) C:\Users\TQTL911\PycharmProjects\Web開發>dir
 驅動器 C 中的卷沒有標籤。
 卷的序列號是 B2D2-AA19

 C:\Users\TQTL911\PycharmProjects\Web開發 的目錄

2018/08/15  15:11    <DIR>          .
2018/08/15  15:11    <DIR>          ..
2018/08/15  11:15    <DIR>          .idea
2018/08/14  16:45    <DIR>          02-web應用程序1
2018/08/15  09:37    <DIR>          03-web應用程序2
2018/08/15  09:37    <DIR>          04-http請求協議1
2018/08/15  09:37    <DIR>          05-http請求協議2
2018/08/15  09:37    <DIR>          06-http協議之響應協議
2018/08/15  09:37    <DIR>          07-wsgiref模塊1
2018/08/15  10:01    <DIR>          08-wsgiref模塊2
2018/08/15  08:43    <DIR>          09-DIY一個web框架
2018/08/15  09:51    <DIR>          10-DIY一個web框架2
2018/08/15  11:58    <DIR>          11-DIY一個web框架3
2018/08/15  10:23    <DIR>          12-框架的簡單使用
2018/08/15  11:59    <DIR>          13-擴展框架關於數據庫的操做
2018/08/15  14:46    <DIR>          14-Django簡介
2018/08/15  15:11    <DIR>          mysite
2018/08/15  15:10    <DIR>          tqtl911
2018/08/14  12:05    <DIR>          venv
               0 個文件              0 字節
              19 個目錄 86,498,488,320 可用字節

(venv) C:\Users\TQTL911\PycharmProjects\Web開發>cd mysite

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>dir
 驅動器 C 中的卷沒有標籤。
 卷的序列號是 B2D2-AA19

 C:\Users\TQTL911\PycharmProjects\Web開發\mysite 的目錄

2018/08/15  15:11    <DIR>          .
2018/08/15  15:11    <DIR>          ..
2018/08/15  15:11               553 manage.py
2018/08/15  15:11    <DIR>          mysite
               1 個文件            553 字節
               3 個目錄 86,498,291,712 可用字節

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>python3 manage.py startapp blog
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ModuleNotFoundError: No module named 'django'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    ) from exc
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>python manage.py startapp blog

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>python manage.py startapp app01

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>python manage.py runserver 127.0.0.1:19939
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 15, 2018 - 15:21:06
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:19939/
Quit the server with CTRL-BREAK.
[15/Aug/2018 15:21:21] "GET / HTTP/1.1" 200 16348
[15/Aug/2018 15:21:21] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[15/Aug/2018 15:21:21] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[15/Aug/2018 15:21:21] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
[15/Aug/2018 15:21:21] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348
Not Found: /favicon.ico
[15/Aug/2018 15:21:21] "GET /favicon.ico HTTP/1.1" 404 1973

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>pip3 uninstall django
Uninstalling Django-2.1:
  Would remove:
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django-2.1.dist-info\*
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django\*
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.exe
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.py
Proceed (y/n)? y
  Successfully uninstalled Django-2.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>pip3 install django==2.0.1
Collecting django==2.0.1
  Downloading https://files.pythonhosted.org/packages/21/2a/3a0ec97b18d6e8d295142228f03604ac78ea6de05cf9bc3773a74f0b58bb/Django-2.0.1-py3-none-any.whl (
7.1MB)
    100% |████████████████████████████████| 7.1MB 4.5MB/s
Requirement already satisfied: pytz in c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages (from django==2.0.1) (2018.5)
abakus-status-checks 0.0.1 has requirement requests[security]==2.8.1, but you'll have requests 2.19.1 which is incompatible.
Installing collected packages: django
Successfully installed django-2.0.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>pip show django
Name: Django
Version: 2.0.1
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD
Location: c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages
Requires: pytz
Required-by:
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>python manage.py runserver 19939
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 15, 2018 - 15:27:18
Django version 2.0.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:19939/
Quit the server with CTRL-BREAK.
[15/Aug/2018 15:27:23] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:24] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:24] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:24] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:25] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:25] "GET / HTTP/1.1" 200 16559
[15/Aug/2018 15:27:25] "GET / HTTP/1.1" 200 16559

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>pip3 uninstall django==2.0.1
Uninstalling Django-2.0.1:
  Would remove:
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django-2.0.1.dist-info\*
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages\django\*
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.exe
    c:\users\tqtl911\pycharmprojects\lfxc2018\venv\scripts\django-admin.py
Proceed (y/n)? y
  Successfully uninstalled Django-2.0.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>from django.shortcuts import render
'from' 不是內部或外部命令,也不是可運行的程序
或批處理文件。

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>from django.shortcuts import render
'from' 不是內部或外部命令,也不是可運行的程序
或批處理文件。

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>pip3 install Django==2.1
Collecting Django==2.1
  Using cached https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl
Requirement already satisfied: pytz in c:\users\tqtl911\pycharmprojects\lfxc2018\venv\lib\site-packages (from Django==2.1) (2018.5)
abakus-status-checks 0.0.1 has requirement requests[security]==2.8.1, but you'll have requests 2.19.1 which is incompatible.
Installing collected packages: Django
Successfully installed Django-2.1
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\TQTL911\PycharmProjects\Web開發\mysite>python manage.py runserver 19939
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 15, 2018 - 15:31:21
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:19939/
Quit the server with CTRL-BREAK.

16-Django簡單實例

一、經過Pycharm建立Django項目並配置應用app01;

17-靜態文件配置1

一、在Django的settings.py中配置STATICFILES_DIRS;

#此處不修改,約定俗成!
STATIC_URL = '/static/'

#必須叫作這個名稱STATICFILES_DIRS,是一個列表;
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,"statics")
]

二、在新增目錄statics中引入jQuery等靜態文件,static目錄必須放在公共區域,即Django項目的第一層目錄下;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        h4{
            color: red;
        }
    </style>
    <script src="/static/jquery-3.3.1.js"></script>
</head>
<body>
    <h4>Hi,{{ctime}}</h4>
    <script>
        $("h4").click(function () {
            $(this).css('color','green')
        })
    </script>
</body>
</html>

18-靜態文件配置2

一、修改應用app01的路徑至statics;

二、將timer.css以及timer.js文件分離出timer.html,添加至app01目錄下,而後進行引用;

PS:獨立的js文件,默認添加分號但css文件末尾不須要添加分號,不然報錯;

$("h4").click(function () {
    $(this).css('color','green')
});
timer.js
   h4{
        color: red;
    }
timer.css

三、timer.html的文件內容以下(注意js文件與body中html代碼的前後順序):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <script src="/static/jquery-3.3.1.js"></script>
    <link rel="stylesheet" href="/static/app01/timer.css">

</head>
<body>
    <h4>Hi,{{ctime}}</h4>
    <script src="/static/app01/timer.js"></script>
</body>
</html>

19-路由控制之簡單配置

一、Django中的路由概述;

  URL配置(URLconf)就像Django所支撐網站的目錄,它的本質是URL與要爲該URL調用的視圖函數之間的映射表,咱們就是以這種方式告訴Django,對於客戶端發來的某個URL調用哪一段邏輯代碼對應執行;

二、簡單的路由配置;

urls.py;

"""demo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from statics.app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('timer/', views.timer),

    #簡單的路由配置:路徑------>視圖函數;從上至下進行判斷;
    re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
    re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此處分組以後,至關於傳入了兩個參數;year_archive(request,2009)
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,2009,11)
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#摻入3個參數;
]

"""
一些請求的例子:
articles/2005/03/ 請求將匹配列表中的第三個模式。Django 將調用函數views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,由於列表中的第三個模式要求月份應該是兩個數字;
/articles/2003/ 將匹配列表中的第一個模式不是第二個,由於模式按順序匹配,第一個會首先測試是否匹配。請像這樣自由插入一些特殊的狀況來探測匹配的次序;
/articles/2003 不匹配任何一個模式,由於每一個模式要求URL 以一個反斜線結尾;
/articles/2003/03/03/ 將匹配最後一個模式。Django 將調用函數views.article_detail(request, '2003', '03', '03');
"""

views.py

from django.shortcuts import render,HttpResponse

# Create your views here.

def timer(request):
    import time
    ctime = time.time()

    return render(request, "time.html", {"ctime":ctime})

def special_case_2003(request):
    return HttpResponse("special_case_2003")

def year_archive(request,year):
    return HttpResponse(year,"year.....")

def month_archive(request,year,month):
    return HttpResponse(year+"-"+month)

def article_detail(request,year,month,detail):
    return HttpResponse(year+"-"+month+"-"+detail)

三、路由配置的注意事項;

  • 如若從URL中捕獲一個值,只須要在它周圍放置一對圓括號;
  • 不須要添加一個前導的反斜槓,由於每一個URL都有,例如應該是^articles,而不是^/articles;
  • 每一個正則表達式前面的"r"是可選的,可是建議加上,它告訴Python解釋器,該字符串是「原始的」---字符串中任何字符都不該該轉義;

20-路由控制之有名分組

一、有名分組;

  在Python 正則表達式中,命名正則表達式組的語法是(?P<name>pattern),其中name 是組的名稱,pattern 是要匹配的模式;

  下面是以上URLconf 使用命名組的重寫:

注意:views中的函數的順序與urls匹配規則中的的順序要一致,不然報錯!

from django.shortcuts import render,HttpResponse

# Create your views here.

def timer(request):
    import time
    ctime = time.time()

    return render(request, "time.html", {"ctime":ctime})

def special_case_2003(request):
    return HttpResponse("special_case_2003")

def year_archive(request,year):
    return HttpResponse(year,"year.....")

#def month_archive(request,year,month):
#def month_archive(request,y,m):
def month_archive(request,m,y):
    return HttpResponse(y+"-"+m)


def article_detail(request,year,month,detail):
    return HttpResponse(year+"-"+month+"-"+detail)
"""demo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path
from statics.app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('timer/', views.timer),

    #簡單的路由配置:路徑------>視圖函數;從上至下進行判斷;
    re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
    re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此處分組以後,至關於傳入了兩個參數;year_archive(request,2009)
    #re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,2009,11)
    re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,y=2009,m=11)
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#摻入3個參數;
]

"""
一些請求的例子:
articles/2005/03/ 請求將匹配列表中的第三個模式。Django 將調用函數views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,由於列表中的第三個模式要求月份應該是兩個數字;
/articles/2003/ 將匹配列表中的第一個模式不是第二個,由於模式按順序匹配,第一個會首先測試是否匹配。請像這樣自由插入一些特殊的狀況來探測匹配的次序;
/articles/2003 不匹配任何一個模式,由於每一個模式要求URL 以一個反斜線結尾;
/articles/2003/03/03/ 將匹配最後一個模式。Django 將調用函數views.article_detail(request, '2003', '03', '03');
"""

21-路由控制之分發

一、Django路由控制之分發urls.py中include引入闡述(相似於nginx.conf中的自定義文件被nginx的主配置文件nginx.conf使用include進行引入,創建映射關係);

"""demo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path,include

from statics.app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('timer/', views.timer),

    #簡單的路由配置:路徑------>視圖函數;從上至下進行判斷;
    # re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
    # re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此處分組以後,至關於傳入了兩個參數;year_archive(request,2009)
    # #re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,2009,11)
    # re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,y=2009,m=11)
    # re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#摻入3個參數;
    

#分發:注意添加上statics,由於app01當前位於statics目錄下!!!
    re_path(r'^',include("statics.app01.urls")),
    #re_path(r'app01/',include("statics.app01.urls")),
    #re_path(r'app02/',include("app02.urls")),
]

"""
一些請求的例子:
articles/2005/03/ 請求將匹配列表中的第三個模式。Django 將調用函數views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,由於列表中的第三個模式要求月份應該是兩個數字;
/articles/2003/ 將匹配列表中的第一個模式不是第二個,由於模式按順序匹配,第一個會首先測試是否匹配。請像這樣自由插入一些特殊的狀況來探測匹配的次序;
/articles/2003 不匹配任何一個模式,由於每一個模式要求URL 以一個反斜線結尾;
/articles/2003/03/03/ 將匹配最後一個模式。Django 將調用函數views.article_detail(request, '2003', '03', '03');
"""

二、app01下的urls.py;

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# __Author__:TQTL911
# Version:python3.6.6
# Time:2018/8/15 18:10


"""demo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path


from statics.app01 import views

urlpatterns = [

    #簡單的路由配置:路徑------>視圖函數;從上至下進行判斷;
    re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
    re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此處分組以後,至關於傳入了兩個參數;year_archive(request,2009)
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,2009,11)
    #re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,y=2009,m=11)
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#摻入3個參數;

]


"""
一些請求的例子:

articles/2005/03/ 請求將匹配列表中的第三個模式。Django 將調用函數views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,由於列表中的第三個模式要求月份應該是兩個數字;
/articles/2003/ 將匹配列表中的第一個模式不是第二個,由於模式按順序匹配,第一個會首先測試是否匹配。請像這樣自由插入一些特殊的狀況來探測匹配的次序;
/articles/2003 不匹配任何一個模式,由於每一個模式要求URL 以一個反斜線結尾;
/articles/2003/03/03/ 將匹配最後一個模式。Django 將調用函數views.article_detail(request, '2003', '03', '03');
"""

22-路由控制之登陸驗證示例

一、登陸實例驗證演示;

urls.py;

"""demo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path,include

from statics.app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('timer/', views.timer),
    path('login/', views.login),

    #簡單的路由配置:路徑------>視圖函數;從上至下進行判斷;
    # re_path(r'^articles/2003/$',views.special_case_2003),#special_case_2003(request)
    # re_path(r'^articles/([0-9]{4})/$',views.year_archive),#此處分組以後,至關於傳入了兩個參數;year_archive(request,2009)
    # #re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,2009,11)
    # re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,y=2009,m=11)
    # re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#摻入3個參數;


#分發:注意添加上statics,由於app01當前位於statics目錄下!!!
    re_path(r'^',include("statics.app01.urls")),
    #re_path(r'app01/',include("statics.app01.urls")),
    #re_path(r'app02/',include("app02.urls")),
]


"""
一些請求的例子:

articles/2005/03/ 請求將匹配列表中的第三個模式。Django 將調用函數views.month_archive(request, '2005', '03');
/articles/2005/3/ 不匹配任何URL 模式,由於列表中的第三個模式要求月份應該是兩個數字;
/articles/2003/ 將匹配列表中的第一個模式不是第二個,由於模式按順序匹配,第一個會首先測試是否匹配。請像這樣自由插入一些特殊的狀況來探測匹配的次序;
/articles/2003 不匹配任何一個模式,由於每一個模式要求URL 以一個反斜線結尾;
/articles/2003/03/03/ 將匹配最後一個模式。Django 將調用函數views.article_detail(request, '2003', '03', '03');
"""

views.py;

from django.shortcuts import render,HttpResponse

# Create your views here.

def timer(request):
    import time
    ctime = time.time()

    return render(request, "time.html", {"ctime":ctime})

def special_case_2003(request):
    return HttpResponse("special_case_2003")

def year_archive(request,year):
    return HttpResponse(year,"year.....")

def month_archive(request,year,month):
#def month_archive(request,y,m):
#def month_archive(request,m,y):
    #return HttpResponse(y+"-"+m)
    return HttpResponse(year+"-"+month)


def article_detail(request,year,month,detail):
    return HttpResponse(year+"-"+month+"-"+detail)


def login(request):
    print(request.method)
    if request.method =="GET":

        return render(request,"login.html")
    else:
        print(request.GET)
        print(request.POST)
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        if user =="cui" and pwd =="123":
            return HttpResponse('登陸成功!')
        else:
            return HttpResponse('用戶名或者密碼錯誤!')

23-路由控制之反向解析1

一、起個別名;

urlpatterns = [
path('admin/', admin.site.urls),
path('timer/', views.timer),
# path('login/', views.login),
path('login/', views.login,name = "Log"),#給路徑起個別名Log,無論是login.htm仍是login或者login.html;
]

二、HTML文件中的{%   url  "Log"  %}用法;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
<!--<form action="http://127.0.0.1:8000/login/" method="post">-->
<form action="{%  url "Log" %}/" method="post">
    用戶名2:<input type="text" name="user">
    密碼2:<input type="password" name="pwd">
    <input type="submit">
    
</form>
</body>
</html>

24-流程控制之反向解析2

一、在urlpatterns中給路由起個別名好比name = "s_c_2003";

urlpatterns = [

    #簡單的路由配置:路徑------>視圖函數;從上至下進行判斷;
    re_path(r'^articles/2003/$',views.special_case_2003,name = "s_c_2003"),#special_case_2003(request)
    re_path(r'^articles/([0-9]{4})/$',views.year_archive,name = "y_a"),#此處分組以後,至關於傳入了兩個參數;year_archive(request,2009)
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,2009,11)
    #re_path(r'^articles/(?P<y>[0-9]{4})/(?P<m>[0-9]{2})/$',views.month_archive),#此處分組以後,至關於傳入了兩個參數;month_archive(request,y=2009,m=11)
    re_path(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$',views.article_detail)#摻入3個參數;

]

二、views.py中從新進行配置,須要導入reverse模塊;

from django.shortcuts import render,HttpResponse

from django.urls import reverse
# Create your views here.

def timer(request):
    import time
    ctime = time.time()
    url = reverse("s_c_2003")
    url = reverse("y_a", args=(1993,))#當原有匹配格式中出現正則的時候,須要傳入一個與原有格式位數相同的數字;好比1993
    print(url)

25-路由控制之名稱空間1

一、名稱空間的概念初識;

  命名空間(英語:Namespace)是表示標識符的可見範圍。一個標識符可在多個命名空間中定義,它在不一樣命名空間中的含義是互不相干的。這樣,在一個新的命名空間中可定義任何標識符,它們不會與任何已有的標識符發生衝突,由於已有的定義都處於其它命名空間中。

  因爲name沒有做用域,Django在反解URL時,會在項目全局順序搜索,當查找到第一個name指定URL時,當即返回;
  咱們在開發項目時,會常用name屬性反解出URL,當不當心在不一樣的app的urls中定義相同的name時,可能會致使URL反解錯誤,爲了不這種事情發生,引入了命名空間的概念,其本質是添加一個標籤,區別重複命名;

project的urls.py;

urlpatterns = [
    re_path(r'^admin/', admin.site.urls),
    re_path(r'^app01/', include("app01.urls",namespace="app01")),
    re_path(r'^app02/', include("app02.urls",namespace="app02")),
]

app01.urls;

urlpatterns = [
    re_path(r'^index/', index,name="index"),
]

app02.urls;

urlpatterns = [
    re_path(r'^index/', index,name="index"),
]

app01.views.py;

from django.shortcuts import render,HttpResponse

# Create your views here.
from django.urls import reverse
def index(request):
    #return HttpResponse("index1,OK")
    return HttpResponse(reverse("app01:index"))

app02.views.py;

from django.shortcuts import render,HttpResponse

# Create your views here.
from django.urls import reverse
def index(request):
    #return HttpResponse("index2,OK")
    return HttpResponse(reverse("app02:index"))

26-路由控制之名稱空間2

一、Django2.0的名稱空間名稱與Django1.0有所不一樣——以元組的形式進行傳值;

    re_path(r'^app01/',include(("statics.app01.urls","app01"))),#引入名稱空間的概念;
    re_path(r'^app02/',include(("statics.app02.urls","app02"))),#引入名稱空間的概念;

27-url控制器之path方法

一、基本示例;

from django.urls import path  
from . import views  
urlpatterns = [  
    path('articles/2003/', views.special_case_2003),  
    path('articles/<int:year>/', views.year_archive),  
    path('articles/<int:year>/<int:month>/', views.month_archive),  
    path('articles/<int:year>/<int:month>/<slug>/', views.article_detail),  
]  
  • 使用尖括號(<>)從url中取值;
  • 捕獲值中能夠包含一個轉化器類型(Content Type),好比<int:year>捕獲了一個整數變量;
  • 無需添加「前導斜槓」;

二、Path轉化器;

Django默認支持5個轉化器;

  • str,匹配除了路徑分隔符(/)以外的非空字符串,這是默認的形式;
  • int,匹配正整數,包含0;
  • slug,匹配字母、數字以及橫槓、下劃線組成的字符串;
  • uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00;
  • path,匹配任何非空字符串,包含了路徑分隔符;

 

28-path的自定義轉換器

一、path支持自定義轉換器;

 對於一些複雜或者複用的須要,能夠定義本身的轉化器,轉化器是一個類或接口,它的要求有三點:

  • regex 類屬性,默認規定的名稱,不可修改,字符串類型;
  • to_python(self, value) 方法,value是由類屬性 regex 所匹配到的字符串,返回具體的Python變量值,以供Django傳遞到對應的視圖函數中;
  • to_url(self, value) 方法,和 to_python 相反,value是一個具體的Python變量值,返回其字符串,一般用於url反向引用;
class FourDigitYearConverter:  
    regex = '[0-9]{4}'  
    def to_python(self, value):  
        return int(value)  
    def to_url(self, value):  
        return '%04d' % value  

二、將register_converter註冊到URL配置中;

from django.urls import register_converter, path  
from . import converters, views  
register_converter(converters.FourDigitYearConverter, 'yyyy')  
urlpatterns = [  
    path('articles/2003/', views.special_case_2003),  
    path('articles/<yyyy:year>/', views.year_archive),  
    ...  
]  

29-url控制總結

一、路由控制之簡單配置;

二、路由控制之有名分組;

三、路由控制之分發include引入外部文件;

四、路由控制之登陸驗證;

五、路由控制之反向解析;

六、路由控制之名稱空間namespace;

七、路由控制之path;

八、路由控制之自定義轉換器;

30-視圖層之請求對象

一、Django中視圖函數初識; 

 Django中的視圖函數,是一個簡單的Python 函數,它接受Web請求而且返回Web響應。響應能夠是一張網頁的HTML內容,一個重定向,一個404錯誤,一個XML文檔,或者一張圖片. . . 是任何東西均可以。不管視圖自己包含什麼邏輯,都要返回響應,代碼寫在哪裏也無所謂,只要它在咱們的Python目錄下面,除此以外沒有更多的要求了——能夠說「沒有什麼神奇的地方」。爲了將代碼放在某處,約定是將視圖函數放置在項目或應用程序目錄中的名爲views.py的文件中;

二、request屬性;

  • HttpRequest.GET;
  • HttpRequest.POST;
  • HttpRequest.body;
  • HttpRequest.path;
  • HttpRequest.method;
  • HttpRequest.encoding;
  • HttpRequest.META;
  • HttpRequest.FILES;
  • HttpRequest.COOKIES;
  • HttpRequest.session;
  • HttpRequest.user;
1.HttpRequest.GET

  一個相似於字典的對象,包含 HTTP GET 的全部參數,詳情請參考 QueryDict 對象;

2.HttpRequest.POST

  一個相似於字典的對象,若是請求中包含表單數據,則將這些數據封裝成 QueryDict 對象;

  POST 請求能夠帶有空的 POST 字典 —— 若是經過 HTTP POST 方法發送一個表單,可是表單中沒有任何的數據,QueryDict 對象依然會被建立。
   所以,不該該使用 if request.POST  來檢查使用的是不是POST 方法;應該使用 if request.method == "POST"
  另外:若是使用 POST 上傳文件的話,文件信息將包含在 FILES 屬性中。
   
   注意:鍵值對的值是多個的時候,好比checkbox類型的input標籤,select標籤,須要用:
        request.POST.getlist("hobby")

3.HttpRequest.body

  一個字符串,表明請求報文的主體。在處理非 HTTP 形式的報文時很是有用,例如:二進制圖片、XML,Json等。
  可是,若是要處理表單數據的時候,推薦仍是使用 HttpRequest.POST 。


4.HttpRequest.path

  一個字符串,表示請求的路徑組件(不含域名)。
  例如:"/music/bands/the_beatles/"

5.HttpRequest.method

  一個字符串,表示請求使用的HTTP 方法。必須使用大寫。
  例如:"GET""POST"


6.HttpRequest.encoding

  一個字符串,表示提交的數據的編碼方式(若是爲 None 則表示使用 DEFAULT_CHARSET 的設置,默認爲 'utf-8')。
   這個屬性是可寫的,你能夠修改它來修改訪問表單數據使用的編碼。
   接下來對屬性的任何訪問(例如從 GET 或 POST 中讀取數據)將使用新的 encoding 值。
   若是你知道表單數據的編碼不是 DEFAULT_CHARSET ,則使用它。


7.HttpRequest.META

   一個標準的Python 字典,包含全部的HTTP 首部。具體的頭部信息取決於客戶端和服務器,下面是一些示例:

    CONTENT_LENGTH —— 請求的正文的長度(是一個字符串)。
    CONTENT_TYPE —— 請求的正文的MIME 類型。
    HTTP_ACCEPT —— 響應可接收的Content-Type。
    HTTP_ACCEPT_ENCODING —— 響應可接收的編碼。
    HTTP_ACCEPT_LANGUAGE —— 響應可接收的語言。
    HTTP_HOST —— 客服端發送的HTTP Host 頭部。
    HTTP_REFERER —— Referring 頁面。
    HTTP_USER_AGENT —— 客戶端的user-agent 字符串。
    QUERY_STRING —— 單個字符串形式的查詢字符串(未解析過的形式)。
    REMOTE_ADDR —— 客戶端的IP 地址。
    REMOTE_HOST —— 客戶端的主機名。
    REMOTE_USER —— 服務器認證後的用戶。
    REQUEST_METHOD —— 一個字符串,例如"GET""POST"。
    SERVER_NAME —— 服務器的主機名。
    SERVER_PORT —— 服務器的端口(是一個字符串)。
   從上面能夠看到,除 CONTENT_LENGTH 和 CONTENT_TYPE 以外,請求中的任何 HTTP 首部轉換爲 META 的鍵時,
    都會將全部字母大寫並將鏈接符替換爲下劃線最後加上 HTTP_  前綴。
    因此,一個叫作 X-Bender 的頭部將轉換成 META 中的 HTTP_X_BENDER 鍵。

8.HttpRequest.FILES

  一個相似於字典的對象,包含全部的上傳文件信息。
   FILES 中的每一個鍵爲<input type="file" name="" /> 中的name,值則爲對應的數據。
  注意,FILES 只有在請求的方法爲POST 且提交的<form> 帶有enctype="multipart/form-data" 的狀況下才會
   包含數據。不然,FILES 將爲一個空的相似於字典的對象。


9.HttpRequest.COOKIES

  一個標準的Python 字典,包含全部的cookie。鍵和值都爲字符串。

10.HttpRequest.session

   一個既可讀又可寫的相似於字典的對象,表示當前的會話。只有當Django 啓用會話的支持時纔可用。
    完整的細節參見會話的文檔。


11.HttpRequest.user(用戶認證組件下使用)

  一個 AUTH_USER_MODEL 類型的對象,表示當前登陸的用戶。

  若是用戶當前沒有登陸,user 將設置爲 django.contrib.auth.models.AnonymousUser 的一個實例。你能夠經過 is_authenticated() 區分它們。

    例如:

    if request.user.is_authenticated():
        # Do something for logged-in users.
    else:
        # Do something for anonymous users.


       user 只有當Django 啓用 AuthenticationMiddleware 中間件時纔可用。

     -------------------------------------------------------------------------------------

    匿名用戶
    class models.AnonymousUser

    django.contrib.auth.models.AnonymousUser 類實現了django.contrib.auth.models.User 接口,但具備下面幾個不一樣點:

    id 永遠爲None。
    username 永遠爲空字符串。
    get_username() 永遠返回空字符串。
    is_staff 和 is_superuser 永遠爲False。
    is_active 永遠爲 False。
    groups 和 user_permissions 永遠爲空。
    is_anonymous() 返回True 而不是False。
    is_authenticated() 返回False 而不是True。
    set_password()、check_password()、save() 和delete() 引起 NotImplementedError。
    New in Django 1.8:
    新增 AnonymousUser.get_username() 以更好地模擬 django.contrib.auth.models.User。

三、request的經常使用方法;

  • HttpRequest.get_full_path();
  • HttpRequest.is_ajax();

settings.py註釋MIDDLEWARE列表中的# 'django.middleware.csrf.CsrfViewMiddleware',

urls.py配置;

views.py;

from django.shortcuts import render,HttpResponse

# Create your views here.
""
"""
URL格式:
協議://IP:PORT/a1/b2/?Get請求數據
"""
def index(request):
    print("method",request.method)#GET請求;
    print(request.GET)#<QueryDict: {'name': ['cuixiaozhao'], 'age': ['26']}>
    print(request.POST)#<QueryDict: {'name': ['lijingping'], 'age': ['22']}>
    print(request.GET.get("name"))#cuixiaozhao
    print(request.POST.get("age"))#22

    print(request.path)#/index/name=cuixiaozhao&age=26

    print(request.get_full_path())#/index/name%3Dcuixiaozhao&age%3D26


    return render(request,"index.html")

操做日誌:

"D:\Program\PyCharm 2018.1.4\bin\runnerw.exe" C:\Users\TQTL911\PycharmProjects\views_demo\venv\Scripts\python.exe C:/Users/TQTL911/PycharmProjects/views_demo/manage.py runserver 8000
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 16, 2018 - 10:55:43
Django version 2.1, using settings 'views_demo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
method GET
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
[16/Aug/2018 10:55:46] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
Not Found: /name=cuixiaozhao&age=26
[16/Aug/2018 10:56:12] "GET /name=cuixiaozhao&age=26 HTTP/1.1" 404 2236
[16/Aug/2018 10:56:19] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
method GET
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
[16/Aug/2018 10:57:15] "POST /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
method POST
<QueryDict: {}>
<QueryDict: {'name': ['lijingping'], 'age': ['23']}>
None
23
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
method GET
[16/Aug/2018 10:57:38] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
method GET
[16/Aug/2018 10:57:59] "GET /index/name=cuixiaozhao&age=26 HTTP/1.1" 200 326
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/name=cuixiaozhao&age=26
/index/name%3Dcuixiaozhao&age%3D26
[16/Aug/2018 10:58:25] "GET /index/ HTTP/1.1" 200 326
method GET
<QueryDict: {}>
<QueryDict: {}>
None
None
/index/
/index/
[16/Aug/2018 10:58:59] "GET /index/?name=%22cuixiaozhao%22&age=%2226%22 HTTP/1.1" 200 326
method GET
<QueryDict: {'name': ['"cuixiaozhao"'], 'age': ['"26"']}>
<QueryDict: {}>
"cuixiaozhao"
None
/index/
/index/?name=%22cuixiaozhao%22&age=%2226%22
method GET
<QueryDict: {'name': ['cuixiaozhao'], 'age': ['26']}>
<QueryDict: {}>
cuixiaozhao
None
/index/
/index/?name=cuixiaozhao&age=26
[16/Aug/2018 10:59:20] "GET /index/?name=cuixiaozhao&age=26 HTTP/1.1" 200 326
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
August 16, 2018 - 10:59:53
Django version 2.1, using settings 'views_demo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

31-視圖響應對象

一、HttpResponse對象的三種主要形式;

  • HttpResponse();
  • render();
  • redirect();

二、render()方法,由於html文件中引用了{{ctime}}屬性;

from django.shortcuts import render,HttpResponse

# Create your views here.
""
"""
URL格式:
協議://IP:PORT/a1/b2/?Get請求數據;
"""
def index(request):
    print("method",request.method)#GET請求;
    print(request.GET)#<QueryDict: {'name': ['cuixiaozhao'], 'age': ['26']}>
    print(request.POST)#<QueryDict: {'name': ['lijingping'], 'age': ['22']}>
    print(request.GET.get("name"))#cuixiaozhao
    print(request.POST.get("age"))#22

    print(request.path)#/index/name=cuixiaozhao&age=26

    print(request.get_full_path())#/index/name%3Dcuixiaozhao&age%3D26


    #return HttpResponse("cuixiaozhao ")

    import time
    ctime = time.time()


    #return HttpResponse("<h1>lijingping</h1> ")
    return render(request,"index.html",{"ctime":ctime})#本質同上,return HttpResponse("xxxx")
"""
帶有{{}}的HTML文件在Django中稱之爲template模板文件;
"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
<form action="" method="post">
    姓名:<input type="text" name="name">
    年齡:<input type="text" name="age">
    <input type="submit"></input>
</form>
    <p>{{ ctime }}</p>
</body>
</html>

32-模版語法之變量

一、Django中的模板語言的深度查詢;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <h1>index</h1>
<p>{{ name }}</p>
<p>{{ num }}</p>
<p>{{ info }}</p>
<p>{{ cxz }}</p>
<p>{{ ljp }}</p>
<p>{{ person_list }}</p>
<p>{{ bool }}</p>
<p>{{ list_num }}</p>
    <hr>
深度查詢
<p>{{ list_num.1 }}</p>
<p>{{ info.name }}</p>
</body>
</html>

二、locals()方法的引入;

from django.shortcuts import render

# Create your views here.
def index(request):
    """
    模板語法只有兩種:
    一、渲染變量{{ name }}
    二、渲染標籤{% age % }
    :param request:
    :return:
    """
    name = "cuixiaozhao"
    num = 10
    list_num = [1,2,3,4]
    info = {"name":"cuixiaozhao","age":26}
    bool = True
    class Person(object):
        def __init__(self,name,age):
            self.name = name
            self.age = age

    cxz = Person("崔曉昭",26)
    ljp = Person("李靜瓶",22)
    person_list = [cxz,ljp]
    #return render(request,"index.html",{"name":name})
    return render(request,"index.html",locals())

33-過濾器

一、Django中的模板過濾器初識;

語法:{{object|fileter_name:param}};算了,我仍是說人話吧:{{對象|過濾器的名稱:屬性值}}

  • default;
  • length;
  • filesizeformat;
  • date;
  • slice;
  • truncatechars;
  • safe;

  Django的模板中會對HTML標籤和JS等語法標籤進行自動轉義,緣由顯而易見,這樣是爲了安全。可是有的時候咱們可能不但願這些HTML元素被轉義,好比咱們作一個內容管理系統,後臺添加的文章中是通過修飾的,這些修飾多是經過一個相似於FCKeditor編輯加註了HTML修飾符的文本,若是自動轉義的話顯示的就是保護HTML標籤的源文件。爲了在Django中關閉HTML的自動轉義有兩種方式,若是是一個單獨的變量咱們能夠經過過濾器「|safe」的方式告訴Django這段代碼是安全的沒必要轉義。好比:

  • truncatewords
from django.shortcuts import render

# Create your views here.
def index(request):
    """
    模板語法只有兩種:
    一、渲染變量{{ name }}
    二、渲染標籤{% age % }
    :param request:
    :return:
    """
    name = "cuixiaozhao"
    num = 10
    list_num = [1,2,3,4]
    info = {"name":"cuixiaozhao","age":26}
    bool = True
    class Person(object):
        def __init__(self,name,age):
            self.name = name
            self.age = age

    cxz = Person("崔曉昭",26)
    ljp = Person("李靜瓶",22)
    person_list = [cxz,ljp]
    #person_list = []
    #return render(request,"index.html",{"name":name})
    import datetime
    now = datetime.datetime.now()
    file_size = 123456
    text = "Hello Python hi LuffyCity Go Java Linux"
    link = "<a href ="" >link</a>"#Django自行作轉義,爲了安全;

    ###############過濾器

    return render(request,"index.html",locals())
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <h1>index</h1>
<p>{{ name }}</p>
<p>{{ num }}</p>
<p>{{ info }}</p>
<p>{{ cxz }}</p>
<p>{{ ljp }}</p>
<p>{{ person_list }}</p>
<p>{{ bool }}</p>
<p>{{ list_num }}</p>
    <hr>
深度查詢
<p>{{ list_num.1 }}</p>
<p>{{ info.name }}</p>
    <h3>Django內置的過濾器初識</h3>
    <p>{{ now|date }}</p>
    <p>{{ now|date:"Y-m-d" }}</p>
    <p>{{ person_list|default:"數據此刻爲空" }}</p>
    <p>{{ file_size|filesizeformat }}</p>
    <p>{{ text|truncatechars:9 }}</p>
    <p>{{ text|truncatewords:3 }}</p>
    <p>{{ link|safe }}</p>
    <p>{{list_num.0|add:100  }}</p>
    <p>{{ info.name|upper}}</p>
</body>
</html>

34-模版語法之標籤

一、Django模板之標籤初識;

  • for標籤;
  • for...empty標籤;
  • if標籤;
  • with標籤;
  • crsf_token(這個標籤用於跨站請求僞造保護);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>
    <h1>index</h1>
<p>{{ name }}</p>
<p>{{ num }}</p>
<p>{{ info }}</p>
<p>{{ cxz }}</p>
<p>{{ ljp }}</p>
<p>{{ person_list }}</p>
<p>{{ bool }}</p>
<p>{{ list_num }}</p>
    <hr>
深度查詢
<p>{{ list_num.1 }}</p>
<p>{{ info.name }}</p>
    <hr>
    <h3>Django內置的過濾器初識</h3>
    <p>{{ now|date }}</p>
    <p>{{ now|date:"Y-m-d" }}</p>
    <p>{{ person_list|default:"數據此刻爲空" }}</p>
    <p>{{ file_size|filesizeformat }}</p>
    <p>{{ text|truncatechars:9 }}</p>
    <p>{{ text|truncatewords:3 }}</p>
    <p>{{ link|safe }}</p>
    <p>{{list_num.0|add:100  }}</p>
    <p>{{ info.name|upper}}</p>
    <hr>
    <h4>for標籤</h4>
    {% for i in list_num %}
        <p>{{ i }}</p>
    {% endfor %}

    {% for keys in info %}
        <p>{{ keys }}</p>
    {% endfor %}

    {% for foo in person_list %}
{#        <p>{{ forloop.counter }} {{ foo.name }},{{ foo.age }}</p>#}
        <p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
    {% endfor %}


    {% for foo in class_list %}
        <p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
        {% empty %}
        <p>列表爲空</p>
    {% endfor %}
    <hr>
    {% if user %}
        <p>
            <a href="">Hi {{ user }},歡迎登陸!</a>
            <a href="">註銷登陸</a>
        </p>
    {% else %}
        <p>
            <a href="">登陸</a>
            <a href="">註冊</a>
        </p>
    {% endif %}
    <hr>
    {% with person_list.1.name as N %}
    {{ N }}
    {% endwith %}
    <hr>

    
</body>
</html>

二、{% csrf_token %}的引入;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">

    </style>
</head>
<body>

<form action="" method="post">
    {% csrf_token %}
    <input type="text" name="user">
    <input type="submit">
</form>
</body>
</html>

 

35-模版語法之自定義標籤與過濾器

一、Django中自定義標籤與過濾器的N大步驟;

  • 一、在settings中的INSTALLED_APPS配置當前app的名稱如app01(注意不能存在重名),否則django沒法找到自定義的simple_tag;

  • 二、在app中建立templatetags包(即包含__init__.py文件,包名只能是templatetags);

  • 三、建立任意 .py 文件,如:my_tag_filter.py;

  • 四、在使用自定義simple_tag和filter的html文件中導入以前建立的 my_tag_filter.py;
  • 五、使用simple_tag和filter(如何調用);

my_tag_filter.py;

#導入;
from django import template

#register變量名是固定的,不用是他其餘;
register = template.Library()


@register.filter
def multi_filter(x,y):
    return x * y



@register.simple_tag()
def multi_tag(m,n,z):
    return m*n*z

二、Django中過濾器與自定義標籤的使用場景與區別;

1)過濾器只能接收2個參數;

2)自定義標籤能夠接收多個參數;

3)過濾器能夠進行if判斷,可是自定義標籤不能夠;

{% if num|multi_filter:30 > 100 %}
    {{ num|multi_filter:30 }}
{% endif %}

36-模版語法之繼承

一、Django模板之繼承;

  Django模版引擎中最強大也是最複雜的部分就是模版繼承了。模版繼承可讓咱們建立一個基本的「骨架」模版,它包含咱們站點中的所有元素,而且能夠定義可以被子模版覆蓋的 blocks ;

base.html;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% block title %}

    {% endblock %}
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <style type="text/css">
        *{
            padding: 0;
            margin: 0;
        }
        .header{
            width: 100%;
            height: 50px;
            background-color: green;
        }
    </style>
</head>
<body>
<div class="header">
    <div class="row">
        <div class="col-md-3">
            {% include 'advertise.html' %}
        </div>
        <div class="col-md-9">
            {% block con %}
                <h1>content</h1>
            {% endblock %}
        </div>
    </div>
</div>
<div class="container"></div>

</body>
</html>

orders.html;

{% extends 'base.html' %}



{% block title %}
    <title>orders</title>
{% endblock %}


{% block con %}
    {{  block.super }}
        <h4>訂單</h4>
{% endblock con %}

index.html;

{% extends 'base.html' %}

{% block title %}
    <title>index</title>
{% endblock %}
{% block con %}
    <h1>index</h1>
    <p>{{ name }}</p>
    <p>{{ num }}</p>
    <p>{{ info }}</p>
    <p>{{ cxz }}</p>
    <p>{{ ljp }}</p>
    <p>{{ person_list }}</p>
    <p>{{ bool }}</p>
    <p>{{ list_num }}</p>
    <hr>
    深度查詢
    <p>{{ list_num.1 }}</p>
    <p>{{ info.name }}</p>
    <hr>
    <h3>Django內置的過濾器初識</h3>
    <p>{{ now|date }}</p>
    <p>{{ now|date:"Y-m-d" }}</p>
    <p>{{ person_list|default:"數據此刻爲空" }}</p>
    <p>{{ file_size|filesizeformat }}</p>
    <p>{{ text|truncatechars:9 }}</p>
    <p>{{ text|truncatewords:3 }}</p>
    <p>{{ link|safe }}</p>
    <p>{{list_num.0|add:100  }}</p>
    <p>{{ info.name|upper}}</p>
    <hr>
    <h4>for標籤</h4>
    {% for i in list_num %}
        <p>{{ i }}</ p>
    {% endfor %}

    {% for keys in info %}
        <p>{{ keys }}</p>
    {% endfor %}

    {% for foo in person_list %}
        <!--       <p>{{ forloop.counter }} {{ foo.name }},{{ foo.age }}</p>-->
        <p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
    {% endfor %}


    {% for foo in class_list %}
        <p>{{ forloop.counter0 }} {{ foo.name }},{{ foo.age }}</p>
    {% empty %}
        <p>列表爲空</p>
    {% endfor %}
    <hr>
    {% if user %}
        <p>
            <a href="">Hi {{ user }},歡迎登陸!</a>
            <a href="">註銷登陸</a>
        </p>
    {% else %}
        <p>
            <a href="">登陸</a>
            <a href="">註冊</a>
        </p>
    {% endif %}
    <hr>
    {% with person_list.1.name as N %}
        {{ N }}
    {% endwith %}
    <hr>

    <hr>
    <h4>Django中的自定義過濾器、標籤</h4>
    {% load my_tag_filter %}
    <p>{{ list_num|multi_filter:20 }}</p>
    <p>{% multi_tag 7 9 11  %}</p>
{% endblock %}

二、Django模板繼承的啓示;

這裏是使用繼承的一些提示:

  • 若是咱們在模版中使用 {% extends %} 標籤,它必須是模版中的第一個標籤。其餘的任何狀況下,模版繼承都將沒法工做;

  • 在base模版中設置越多的 {% block %} 標籤越好。請記住,子模版沒必要定義所有父模版中的blocks,因此,咱們能夠在大多數blocks中填充合理的默認內容,而後,只定義咱們須要的那一個,多一點鉤子總比少一點好;

  • 若是發現咱們本身在大量的模版中複製內容,那可能意味着咱們應該把內容移動到父模版中的一個 {% block %} 中;

  • If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }} will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template;

  • 爲了更好的可讀性,咱們也能夠給你的 {% endblock %} 標籤一個 名字 。例如:

37-ORM簡介

一、Django中的ORM簡介;

  MVC或者MVC框架中包括一個重要的部分,就是ORM,它實現了數據模型與數據庫的解耦,即數據模型的設計不須要依賴於特定的數據庫,經過簡單的配置就能夠輕鬆更換數據庫,這極大的減輕了開發人員的工做量,不須要面對因數據庫變動而致使的無效勞動;
  ORM(Object Relational Mapping)是「對象-關係-映射」的簡稱;

二、SQL中的表;

#sql中的表;                                                      

 #建立表:
     CREATE TABLE employee(                                     
                id INT PRIMARY KEY auto_increment ,                    
                name VARCHAR (20),                                      
                gender BIT default 1,                                  
                birthday DATE ,                                         
                department VARCHAR (20),                                
                salary DECIMAL (8,2) unsigned                    
              );

  #sql中的表紀錄                                                  
  #添加一條表紀錄:                                                          
      INSERT employee (name,gender,birthday,salary,department)            
             VALUES   ("alex",1,"1985-12-12",8000,"保潔部");               
  #查詢一條表紀錄:                                                           
      SELECT * FROM employee WHERE age=24;                               
  #更新一條表紀錄:                                                           
      UPDATE employee SET birthday="1989-10-24" WHERE id=1;              
  #刪除一條表紀錄:                                                          
      DELETE FROM employee WHERE name="alex";

三、Python中的類;

#python的類
class Employee(models.Model):
     id=models.AutoField(primary_key=True)
     name=models.CharField(max_length=32)
     gender=models.BooleanField()
     birthday=models.DateField()
     department=models.CharField(max_length=32)
     salary=models.DecimalField(max_digits=8,decimal_places=2)
 #python的類對象
      #添加一條表紀錄:
          emp=Employee(name="alex",gender=True,birthday="1985-12-12",epartment="保潔部")
          emp.save()
      #查詢一條表紀錄:
          Employee.objects.filter(age=24)
      #更新一條表紀錄:
          Employee.objects.filter(id=1).update(birthday="1989-10-24")
      #刪除一條表紀錄:
          Employee.objects.filter(name="alex").delete()

38-單表操做之生成表模型

一、單表操做的N個主要步驟;

1)建立模型;

from django.db import models

# Create your models here.
class Book(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32,unique=True)
    pub_date = models.DateField()
    price = models.DecimalField(max_digits=8,decimal_places=2)#999999.99
    publish = models.CharField(max_length=22)

2)settings.py文件中的數據庫(提早建立數據庫實例orm)鏈接信息配置(先註釋默認sqllite3的數據鏈接信息配置);

 settings.py;

"""
Django settings for ORM project.

Generated by 'django-admin startproject' using Django 2.1.

For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0uw!%id+y+xv=dm@0v+d(tf-#r!_zm1&ymtb$f2mi$5*6$5a&j'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01.apps.App01Config',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'ORM.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'ORM.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',#數據庫的引擎爲MySQL;
        'NAME': 'orm',#要鏈接的數據庫實例的名稱,鏈接前須要已經完成建立;
        'USER': 'root',#MySQL數據庫的用戶名;
        'PASSWORD': 'Tqtl911!@%*123)',#MySQL數據庫的密碼;
        'HOST': '147.195.221.254',#MySQL數據庫服務器的IP地址;
        'PORT': '3306'#MySQL數據庫的款口號,默認3306;
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

3)項目中pip安裝第三方模塊pymysql;

pip3 install pymysql

4)在項目的根目錄中的__init__.py文件中導入兩條記錄;

import pymysql
pymysql.install_as_MySQLdb()

5 )Django2.0版本,註釋base.py中的內容;

路徑參考:C:\Users\TQTL911\PycharmProjects\ORM\venv\Lib\site-packages\django\db\backends\mysql\base.py;

if version < (1, 3, 7):
    raise ImproperlyConfigured('mysqlclient 1.3.7 or newer is required; you have %s.' % Database.__version__)
"""
MySQL database backend for Django.

Requires mysqlclient: https://pypi.org/project/mysqlclient/
"""
import re

from django.core.exceptions import ImproperlyConfigured
from django.db import utils
from django.db.backends import utils as backend_utils
from django.db.backends.base.base import BaseDatabaseWrapper
from django.utils.functional import cached_property

try:
    import MySQLdb as Database
except ImportError as err:
    raise ImproperlyConfigured(
        'Error loading MySQLdb module.\n'
        'Did you install mysqlclient?'
    ) from err

from MySQLdb.constants import CLIENT, FIELD_TYPE                # isort:skip
from MySQLdb.converters import conversions                      # isort:skip

# Some of these import MySQLdb, so import them after checking if it's installed.
from .client import DatabaseClient                          # isort:skip
from .creation import DatabaseCreation                      # isort:skip
from .features import DatabaseFeatures                      # isort:skip
from .introspection import DatabaseIntrospection            # isort:skip
from .operations import DatabaseOperations                  # isort:skip
from .schema import DatabaseSchemaEditor                    # isort:skip
from .validation import DatabaseValidation                  # isort:skip

version = Database.version_info
#if version < (1, 3, 7):
#    raise ImproperlyConfigured('mysqlclient 1.3.7 or newer is required; you have %s.' % #Database.__version__)


# MySQLdb returns TIME columns as timedelta -- they are more like timedelta in
# terms of actual behavior as they are signed and include days -- and Django
# expects time.
django_conversions = {
    **conversions,
    **{FIELD_TYPE.TIME: backend_utils.typecast_time},
}

# This should match the numerical portion of the version numbers (we can treat
# versions like 5.0.24 and 5.0.24a as the same).
server_version_re = re.compile(r'(\d{1,2})\.(\d{1,2})\.(\d{1,2})')


class CursorWrapper:
    """
    A thin wrapper around MySQLdb's normal cursor class that catches particular
    exception instances and reraises them with the correct types.

    Implemented as a wrapper, rather than a subclass, so that it isn't stuck
    to the particular underlying representation returned by Connection.cursor().
    """
    codes_for_integrityerror = (
        1048,  # Column cannot be null
        1690,  # BIGINT UNSIGNED value is out of range
    )

    def __init__(self, cursor):
        self.cursor = cursor

    def execute(self, query, args=None):
        try:
            # args is None means no string interpolation
            return self.cursor.execute(query, args)
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                raise utils.IntegrityError(*tuple(e.args))
            raise

    def executemany(self, query, args):
        try:
            return self.cursor.executemany(query, args)
        except Database.OperationalError as e:
            # Map some error codes to IntegrityError, since they seem to be
            # misclassified and Django would prefer the more logical place.
            if e.args[0] in self.codes_for_integrityerror:
                raise utils.IntegrityError(*tuple(e.args))
            raise

    def __getattr__(self, attr):
        return getattr(self.cursor, attr)

    def __iter__(self):
        return iter(self.cursor)


class DatabaseWrapper(BaseDatabaseWrapper):
    vendor = 'mysql'
    display_name = 'MySQL'
    # This dictionary maps Field objects to their associated MySQL column
    # types, as strings. Column-type strings can contain format strings; they'll
    # be interpolated against the values of Field.__dict__ before being output.
    # If a column type is set to None, it won't be included in the output.
    data_types = {
        'AutoField': 'integer AUTO_INCREMENT',
        'BigAutoField': 'bigint AUTO_INCREMENT',
        'BinaryField': 'longblob',
        'BooleanField': 'bool',
        'CharField': 'varchar(%(max_length)s)',
        'DateField': 'date',
        'DateTimeField': 'datetime(6)',
        'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
        'DurationField': 'bigint',
        'FileField': 'varchar(%(max_length)s)',
        'FilePathField': 'varchar(%(max_length)s)',
        'FloatField': 'double precision',
        'IntegerField': 'integer',
        'BigIntegerField': 'bigint',
        'IPAddressField': 'char(15)',
        'GenericIPAddressField': 'char(39)',
        'NullBooleanField': 'bool',
        'OneToOneField': 'integer',
        'PositiveIntegerField': 'integer UNSIGNED',
        'PositiveSmallIntegerField': 'smallint UNSIGNED',
        'SlugField': 'varchar(%(max_length)s)',
        'SmallIntegerField': 'smallint',
        'TextField': 'longtext',
        'TimeField': 'time(6)',
        'UUIDField': 'char(32)',
    }

    # For these columns, MySQL doesn't:
    # - accept default values and implicitly treats these columns as nullable
    # - support a database index
    _limited_data_types = (
        'tinyblob', 'blob', 'mediumblob', 'longblob', 'tinytext', 'text',
        'mediumtext', 'longtext', 'json',
    )

    operators = {
        'exact': '= %s',
        'iexact': 'LIKE %s',
        'contains': 'LIKE BINARY %s',
        'icontains': 'LIKE %s',
        'gt': '> %s',
        'gte': '>= %s',
        'lt': '< %s',
        'lte': '<= %s',
        'startswith': 'LIKE BINARY %s',
        'endswith': 'LIKE BINARY %s',
        'istartswith': 'LIKE %s',
        'iendswith': 'LIKE %s',
    }

    # The patterns below are used to generate SQL pattern lookup clauses when
    # the right-hand side of the lookup isn't a raw string (it might be an expression
    # or the result of a bilateral transformation).
    # In those cases, special characters for LIKE operators (e.g. \, *, _) should be
    # escaped on database side.
    #
    # Note: we use str.format() here for readability as '%' is used as a wildcard for
    # the LIKE operator.
    pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\\', '\\\\'), '%%', '\%%'), '_', '\_')"
    pattern_ops = {
        'contains': "LIKE BINARY CONCAT('%%', {}, '%%')",
        'icontains': "LIKE CONCAT('%%', {}, '%%')",
        'startswith': "LIKE BINARY CONCAT({}, '%%')",
        'istartswith': "LIKE CONCAT({}, '%%')",
        'endswith': "LIKE BINARY CONCAT('%%', {})",
        'iendswith': "LIKE CONCAT('%%', {})",
    }

    isolation_levels = {
        'read uncommitted',
        'read committed',
        'repeatable read',
        'serializable',
    }

    Database = Database
    SchemaEditorClass = DatabaseSchemaEditor
    # Classes instantiated in __init__().
    client_class = DatabaseClient
    creation_class = DatabaseCreation
    features_class = DatabaseFeatures
    introspection_class = DatabaseIntrospection
    ops_class = DatabaseOperations
    validation_class = DatabaseValidation

    def get_connection_params(self):
        kwargs = {
            'conv': django_conversions,
            'charset': 'utf8',
        }
        settings_dict = self.settings_dict
        if settings_dict['USER']:
            kwargs['user'] = settings_dict['USER']
        if settings_dict['NAME']:
            kwargs['db'] = settings_dict['NAME']
        if settings_dict['PASSWORD']:
            kwargs['passwd'] = settings_dict['PASSWORD']
        if settings_dict['HOST'].startswith('/'):
            kwargs['unix_socket'] = settings_dict['HOST']
        elif settings_dict['HOST']:
            kwargs['host'] = settings_dict['HOST']
        if settings_dict['PORT']:
            kwargs['port'] = int(settings_dict['PORT'])
        # We need the number of potentially affected rows after an
        # "UPDATE", not the number of changed rows.
        kwargs['client_flag'] = CLIENT.FOUND_ROWS
        # Validate the transaction isolation level, if specified.
        options = settings_dict['OPTIONS'].copy()
        isolation_level = options.pop('isolation_level', 'read committed')
        if isolation_level:
            isolation_level = isolation_level.lower()
            if isolation_level not in self.isolation_levels:
                raise ImproperlyConfigured(
                    "Invalid transaction isolation level '%s' specified.\n"
                    "Use one of %s, or None." % (
                        isolation_level,
                        ', '.join("'%s'" % s for s in sorted(self.isolation_levels))
                    ))
        self.isolation_level = isolation_level
        kwargs.update(options)
        return kwargs

    def get_new_connection(self, conn_params):
        return Database.connect(**conn_params)

    def init_connection_state(self):
        assignments = []
        if self.features.is_sql_auto_is_null_enabled:
            # SQL_AUTO_IS_NULL controls whether an AUTO_INCREMENT column on
            # a recently inserted row will return when the field is tested
            # for NULL. Disabling this brings this aspect of MySQL in line
            # with SQL standards.
            assignments.append('SET SQL_AUTO_IS_NULL = 0')

        if self.isolation_level:
            assignments.append('SET SESSION TRANSACTION ISOLATION LEVEL %s' % self.isolation_level.upper())

        if assignments:
            with self.cursor() as cursor:
                cursor.execute('; '.join(assignments))

    def create_cursor(self, name=None):
        cursor = self.connection.cursor()
        return CursorWrapper(cursor)

    def _rollback(self):
        try:
            BaseDatabaseWrapper._rollback(self)
        except Database.NotSupportedError:
            pass

    def _set_autocommit(self, autocommit):
        with self.wrap_database_errors:
            self.connection.autocommit(autocommit)

    def disable_constraint_checking(self):
        """
        Disable foreign key checks, primarily for use in adding rows with
        forward references. Always return True to indicate constraint checks
        need to be re-enabled.
        """
        self.cursor().execute('SET foreign_key_checks=0')
        return True

    def enable_constraint_checking(self):
        """
        Re-enable foreign key checks after they have been disabled.
        """
        # Override needs_rollback in case constraint_checks_disabled is
        # nested inside transaction.atomic.
        self.needs_rollback, needs_rollback = False, self.needs_rollback
        try:
            self.cursor().execute('SET foreign_key_checks=1')
        finally:
            self.needs_rollback = needs_rollback

    def check_constraints(self, table_names=None):
        """
        Check each table name in `table_names` for rows with invalid foreign
        key references. This method is intended to be used in conjunction with
        `disable_constraint_checking()` and `enable_constraint_checking()`, to
        determine if rows with invalid references were entered while constraint
        checks were off.
        """
        with self.cursor() as cursor:
            if table_names is None:
                table_names = self.introspection.table_names(cursor)
            for table_name in table_names:
                primary_key_column_name = self.introspection.get_primary_key_column(cursor, table_name)
                if not primary_key_column_name:
                    continue
                key_columns = self.introspection.get_key_columns(cursor, table_name)
                for column_name, referenced_table_name, referenced_column_name in key_columns:
                    cursor.execute(
                        """
                        SELECT REFERRING.`%s`, REFERRING.`%s` FROM `%s` as REFERRING
                        LEFT JOIN `%s` as REFERRED
                        ON (REFERRING.`%s` = REFERRED.`%s`)
                        WHERE REFERRING.`%s` IS NOT NULL AND REFERRED.`%s` IS NULL
                        """ % (
                            primary_key_column_name, column_name, table_name,
                            referenced_table_name, column_name, referenced_column_name,
                            column_name, referenced_column_name,
                        )
                    )
                    for bad_row in cursor.fetchall():
                        raise utils.IntegrityError(
                            "The row in table '%s' with primary key '%s' has an invalid "
                            "foreign key: %s.%s contains a value '%s' that does not "
                            "have a corresponding value in %s.%s."
                            % (
                                table_name, bad_row[0], table_name, column_name,
                                bad_row[1], referenced_table_name, referenced_column_name,
                            )
                        )

    def is_usable(self):
        try:
            self.connection.ping()
        except Database.Error:
            return False
        else:
            return True

    @cached_property
    def mysql_server_info(self):
        with self.temporary_connection() as cursor:
            cursor.execute('SELECT VERSION()')
            return cursor.fetchone()[0]

    @cached_property
    def mysql_version(self):
        match = server_version_re.match(self.mysql_server_info)
        if not match:
            raise Exception('Unable to determine MySQL version from version string %r' % self.mysql_server_info)
        return tuple(int(x) for x in match.groups())

    @cached_property
    def mysql_is_mariadb(self):
        # MariaDB isn't officially supported.
        return 'mariadb' in self.mysql_server_info.lower()
base.py

 

6)確保配置文件中的INSTALLED_APPS中寫入咱們建立的app名稱-app01;

7) 經過兩條數據庫遷移命令便可在指定的數據庫中建立表;

python manage.py makemigrations
python manage.py migrate

8)檢查數據表是否建立成功;

 

操做日誌:

Microsoft Windows [版本 10.0.17134.1]
(c) 2018 Microsoft Corporation。保留全部權利。

(venv) C:\Users\TQTL911\PycharmProjects\ORM>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 224, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 12, in <module>
    from django.db.migrations.autodetector import MigrationAutodetector
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\autodetector.py", line 11, in <module>
    from django.db.migrations.questioner import MigrationQuestioner
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\questioner.py", line 9, in <module>
    from .loader import MigrationLoader
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\loader.py", line 8, in <module>
    from django.db.migrations.recorder import MigrationRecorder
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\recorder.py", line 9, in <module>
    class MigrationRecorder:
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\migrations\recorder.py", line 22, in MigrationRecorder
    class Migration(models.Model):
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 87, in __new__
    app_config = apps.get_containing_app_config(module)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\apps\registry.py", line 249, in get_containing_app_config
    self.check_apps_ready()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\apps\registry.py", line 131, in check_apps_ready
    settings.INSTALLED_APPS
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__
    self._setup(name)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\conf\__init__.py", line 44, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\conf\__init__.py", line 107, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Program Files\Python36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "C:\Users\TQTL911\PycharmProjects\ORM\ORM\__init__.py", line 1, in <module>
    import pymysql
ModuleNotFoundError: No module named 'pymysql'

(venv) C:\Users\TQTL911\PycharmProjects\ORM>pip show pymysql
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\TQTL911\PycharmProjects\ORM>pip3 install pymysql
Collecting pymysql
  Using cached https://files.pythonhosted.org/packages/a7/7d/682c4a7da195a678047c8f1c51bb7682aaedee1dca7547883c3993ca9282/PyMySQL-0.9.2-py2.py3-none-any.whl
Collecting cryptography (from pymysql)
  Using cached https://files.pythonhosted.org/packages/f1/01/a144ec664d3f9ae5837bd72c4d11bdd2d8d403318898e4092457e8af9272/cryptography-2.3.1-cp36-cp36m-win_amd64.whl
Collecting asn1crypto>=0.21.0 (from cryptography->pymysql)
  Using cached https://files.pythonhosted.org/packages/ea/cd/35485615f45f30a510576f1a56d1e0a7ad7bd8ab5ed7cdc600ef7cd06222/asn1crypto-0.24.0-py2.py3-none-any.whl
Collecting idna>=2.1 (from cryptography->pymysql)
  Using cached https://files.pythonhosted.org/packages/4b/2a/0276479a4b3caeb8a8c1af2f8e4355746a97fab05a372e4a2c6a6b876165/idna-2.7-py2.py3-none-any.whl
Collecting cffi!=1.11.3,>=1.7 (from cryptography->pymysql)
  Using cached https://files.pythonhosted.org/packages/2f/85/a9184548ad4261916d08a50d9e272bf6f93c54f3735878fbfc9335efd94b/cffi-1.11.5-cp36-cp36m-win_amd64.whl
Collecting six>=1.4.1 (from cryptography->pymysql)
  Using cached https://files.pythonhosted.org/packages/67/4b/141a581104b1f6397bfa78ac9d43d8ad29a7ca43ea90a2d863fe3056e86a/six-1.11.0-py2.py3-none-any.whl
Collecting pycparser (from cffi!=1.11.3,>=1.7->cryptography->pymysql)
  Using cached https://files.pythonhosted.org/packages/8c/2d/aad7f16146f4197a11f8e91fb81df177adcc2073d36a17b1491fd09df6ed/pycparser-2.18.tar.gz
Installing collected packages: asn1crypto, idna, pycparser, cffi, six, cryptography, pymysql
  Running setup.py install for pycparser ... done
Successfully installed asn1crypto-0.24.0 cffi-1.11.5 cryptography-2.3.1 idna-2.7 pycparser-2.18 pymysql-0.9.2 six-1.11.0
You are using pip version 10.0.1, however version 18.0 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

(venv) C:\Users\TQTL911\PycharmProjects\ORM>python manage.py makemigrations
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
No changes detected

(venv) C:\Users\TQTL911\PycharmProjects\ORM>python manage.py migrate
(0.012) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.332) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.017) SELECT @@sql_mode; args=None
(0.015) SHOW FULL TABLES; args=None
(0.013) SHOW FULL TABLES; args=None
Operations to perform:
  Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
(0.018) SHOW FULL TABLES; args=None
CREATE TABLE `django_migrations` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `app` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `applied` datetime(6) NOT NULL); (params None)
(0.215) CREATE TABLE `django_migrations` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `app` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `applied` datetime(6) NOT NULL); args=None
(0.366) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
(0.310) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
(0.156) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
(0.158) SELECT engine FROM information_schema.tables WHERE table_name = 'django_migrations'; args=['django_migrations']
CREATE TABLE `django_content_type` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL, `app_label` varchar(100) NOT NULL, `model` varchar(100) NOT NULL); (params None)
(0.170) CREATE TABLE `django_content_type` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(100) NOT NULL, `app_label` varchar(100) NOT NULL, `model` varchar(100) NOT NULL); args=None
(0.263) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
(0.222) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
(0.220) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
(0.176) SELECT engine FROM information_schema.tables WHERE table_name = 'django_content_type'; args=['django_content_type']
ALTER TABLE `django_content_type` ADD CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (`app_label`, `model`); (params ())
(0.234) ALTER TABLE `django_content_type` ADD CONSTRAINT django_content_type_app_label_model_76bd3d3b_uniq UNIQUE (`app_label`, `model`); args=()
(0.012) SHOW FULL TABLES; args=None
(0.158) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('contenttypes', '0001_initial', '2018-08-16 15:08:06.854620'); args=['contenttypes', '0001_initial', '2018-08-16 15:08:06.854620']
  Applying contenttypes.0001_initial... OK
CREATE TABLE `auth_permission` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(50) NOT NULL, `content_type_id` integer NOT NULL, `codename` varchar(100) NOT NULL); (params None)
(0.122) CREATE TABLE `auth_permission` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(50) NOT NULL, `content_type_id` integer NOT NULL, `codename` varchar(100) NOT NULL); args=None
(0.073) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
(0.178) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
(0.161) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
(0.162) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_permission'; args=['auth_permission']
CREATE TABLE `auth_group` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(80) NOT NULL UNIQUE); (params None)
(0.175) CREATE TABLE `auth_group` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `name` varchar(80) NOT NULL UNIQUE); args=None
(0.169) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group'; args=['auth_group']
(0.147) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group'; args=['auth_group']
CREATE TABLE `auth_group_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `group_id` integer NOT NULL, `permission_id` integer NOT NULL); (params None)
(0.215) CREATE TABLE `auth_group_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `group_id` integer NOT NULL, `permission_id` integer NOT NULL); args=None
(0.111) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group_permissions'; args=['auth_group_permissions']
(0.102) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group_permissions'; args=['auth_group_permissions']
(0.146) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_group_permissions'; args=['auth_group_permissions']
CREATE TABLE `auth_user` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `password` varchar(128) NOT NULL, `last_login` datetime(6) NOT NULL, `is_superuser` bool NOT NULL, `username` varchar(30) NOT NULL
 UNIQUE, `first_name` varchar(30) NOT NULL, `last_name` varchar(30) NOT NULL, `email` varchar(75) NOT NULL, `is_staff` bool NOT NULL, `is_active` bool NOT NULL, `date_joined` datetime(6) NOT NULL); (params
None)
(0.206) CREATE TABLE `auth_user` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `password` varchar(128) NOT NULL, `last_login` datetime(6) NOT NULL, `is_superuser` bool NOT NULL, `username` varchar(30)
NOT NULL UNIQUE, `first_name` varchar(30) NOT NULL, `last_name` varchar(30) NOT NULL, `email` varchar(75) NOT NULL, `is_staff` bool NOT NULL, `is_active` bool NOT NULL, `date_joined` datetime(6) NOT NULL);
args=None
(0.158) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.166) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.139) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.096) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.141) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.125) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.188) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.210) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.154) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.163) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
(0.186) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user'; args=['auth_user']
CREATE TABLE `auth_user_groups` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `group_id` integer NOT NULL); (params None)
(0.194) CREATE TABLE `auth_user_groups` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `group_id` integer NOT NULL); args=None
(0.104) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_groups'; args=['auth_user_groups']
(0.115) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_groups'; args=['auth_user_groups']
(0.166) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_groups'; args=['auth_user_groups']
CREATE TABLE `auth_user_user_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `permission_id` integer NOT NULL); (params None)
(0.178) CREATE TABLE `auth_user_user_permissions` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `user_id` integer NOT NULL, `permission_id` integer NOT NULL); args=None
(0.138) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_user_permissions'; args=['auth_user_user_permissions']
(0.146) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_user_permissions'; args=['auth_user_user_permissions']
(0.079) SELECT engine FROM information_schema.tables WHERE table_name = 'auth_user_user_permissions'; args=['auth_user_user_permissions']
ALTER TABLE `auth_permission` ADD CONSTRAINT `auth_permission_content_type_id_2f476e4b_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); (params ())
(0.156) ALTER TABLE `auth_permission` ADD CONSTRAINT `auth_permission_content_type_id_2f476e4b_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); args=()
ALTER TABLE `auth_permission` ADD CONSTRAINT auth_permission_content_type_id_codename_01ab375a_uniq UNIQUE (`content_type_id`, `codename`); (params ())
(0.300) ALTER TABLE `auth_permission` ADD CONSTRAINT auth_permission_content_type_id_codename_01ab375a_uniq UNIQUE (`content_type_id`, `codename`); args=()
ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissions_group_id_b120cbf9_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); (params ())
(0.215) ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissions_group_id_b120cbf9_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); args=()
ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); (params ())
(0.280) ALTER TABLE `auth_group_permissions` ADD CONSTRAINT `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); args=()
ALTER TABLE `auth_group_permissions` ADD CONSTRAINT auth_group_permissions_group_id_permission_id_0cd325b0_uniq UNIQUE (`group_id`, `permission_id`); (params ())
(0.205) ALTER TABLE `auth_group_permissions` ADD CONSTRAINT auth_group_permissions_group_id_permission_id_0cd325b0_uniq UNIQUE (`group_id`, `permission_id`); args=()
ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_user_id_6a12ed8b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); (params ())
(0.252) ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_user_id_6a12ed8b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); args=()
ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_group_id_97559544_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); (params ())
(0.210) ALTER TABLE `auth_user_groups` ADD CONSTRAINT `auth_user_groups_group_id_97559544_fk_auth_group_id` FOREIGN KEY (`group_id`) REFERENCES `auth_group` (`id`); args=()
ALTER TABLE `auth_user_groups` ADD CONSTRAINT auth_user_groups_user_id_group_id_94350c0c_uniq UNIQUE (`user_id`, `group_id`); (params ())
(0.205) ALTER TABLE `auth_user_groups` ADD CONSTRAINT auth_user_groups_user_id_group_id_94350c0c_uniq UNIQUE (`user_id`, `group_id`); args=()
ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); (params ())
(0.212) ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permissions_user_id_a95ead1b_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); args=()
ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); (params ())
(0.162) ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT `auth_user_user_permi_permission_id_1fbb5f2c_fk_auth_perm` FOREIGN KEY (`permission_id`) REFERENCES `auth_permission` (`id`); args=()
ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_14a6b632_uniq UNIQUE (`user_id`, `permission_id`); (params ())
(0.161) ALTER TABLE `auth_user_user_permissions` ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_14a6b632_uniq UNIQUE (`user_id`, `permission_id`); args=()
(0.014) SHOW FULL TABLES; args=None
(0.121) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0001_initial', '2018-08-16 15:08:14.269528'); args=['auth', '0001_initial', '2018-08-16 15:08:14.269528']
  Applying auth.0001_initial... OK
CREATE TABLE `django_admin_log` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `action_time` datetime(6) NOT NULL, `object_id` longtext NULL, `object_repr` varchar(200) NOT NULL, `action_flag` smallint
UNSIGNED NOT NULL, `change_message` longtext NOT NULL, `content_type_id` integer NULL, `user_id` integer NOT NULL); (params None)
(0.193) CREATE TABLE `django_admin_log` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `action_time` datetime(6) NOT NULL, `object_id` longtext NULL, `object_repr` varchar(200) NOT NULL, `action_flag` s
mallint UNSIGNED NOT NULL, `change_message` longtext NOT NULL, `content_type_id` integer NULL, `user_id` integer NOT NULL); args=None
(0.168) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.143) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.174) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.147) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.155) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.132) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.128) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
(0.104) SELECT engine FROM information_schema.tables WHERE table_name = 'django_admin_log'; args=['django_admin_log']
ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_content_type_id_c4bce8eb_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); (params ())
(0.125) ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_content_type_id_c4bce8eb_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`id`); args=()
ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); (params ())
(0.165) ALTER TABLE `django_admin_log` ADD CONSTRAINT `django_admin_log_user_id_c564eba6_fk_auth_user_id` FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`); args=()
(0.021) SHOW FULL TABLES; args=None
(0.121) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('admin', '0001_initial', '2018-08-16 15:08:16.106198'); args=['admin', '0001_initial', '2018-08-16 15:08:16.106198']
  Applying admin.0001_initial... OK
(0.014) SHOW FULL TABLES; args=None
(0.119) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('admin', '0002_logentry_remove_auto_add', '2018-08-16 15:08:16.288329'); args=['admin', '0002_logentry_remove_auto_add', '2018-08-1
6 15:08:16.288329']
  Applying admin.0002_logentry_remove_auto_add... OK
(0.014) SHOW FULL TABLES; args=None
(0.106) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('admin', '0003_logentry_add_action_flag_choices', '2018-08-16 15:08:16.470961'); args=['admin', '0003_logentry_add_action_flag_choi
ces', '2018-08-16 15:08:16.470961']
  Applying admin.0003_logentry_add_action_flag_choices... OK
CREATE TABLE `app01_book` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(32) NOT NULL UNIQUE, `pub_date` date NOT NULL, `price` numeric(8, 2) NOT NULL, `publish` varchar(22) NOT NULL); (
params None)
(0.119) CREATE TABLE `app01_book` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `title` varchar(32) NOT NULL UNIQUE, `pub_date` date NOT NULL, `price` numeric(8, 2) NOT NULL, `publish` varchar(22) NOT
NULL); args=None
(0.124) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.128) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.114) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.094) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.105) SELECT engine FROM information_schema.tables WHERE table_name = 'app01_book'; args=['app01_book']
(0.015) SHOW FULL TABLES; args=None
(0.166) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('app01', '0001_initial', '2018-08-16 15:08:17.320430'); args=['app01', '0001_initial', '2018-08-16 15:08:17.320430']
  Applying app01.0001_initial... OK
ALTER TABLE `django_content_type` MODIFY `name` varchar(100) NULL; (params [])
(0.243) ALTER TABLE `django_content_type` MODIFY `name` varchar(100) NULL; args=[]
ALTER TABLE `django_content_type` DROP COLUMN `name`; (params ())
(0.142) ALTER TABLE `django_content_type` DROP COLUMN `name`; args=()
(0.016) SHOW FULL TABLES; args=None
(0.165) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('contenttypes', '0002_remove_content_type_name', '2018-08-16 15:08:17.989002'); args=['contenttypes', '0002_remove_content_type_nam
e', '2018-08-16 15:08:17.989002']
  Applying contenttypes.0002_remove_content_type_name... OK
ALTER TABLE `auth_permission` MODIFY `name` varchar(255) NOT NULL; (params [])
(0.175) ALTER TABLE `auth_permission` MODIFY `name` varchar(255) NOT NULL; args=[]
(0.013) SHOW FULL TABLES; args=None
(0.144) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0002_alter_permission_name_max_length', '2018-08-16 15:08:18.391744'); args=['auth', '0002_alter_permission_name_max_lengt
h', '2018-08-16 15:08:18.391744']
  Applying auth.0002_alter_permission_name_max_length... OK
ALTER TABLE `auth_user` MODIFY `email` varchar(254) NOT NULL; (params [])
(0.165) ALTER TABLE `auth_user` MODIFY `email` varchar(254) NOT NULL; args=[]
(0.019) SHOW FULL TABLES; args=None
(0.133) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0003_alter_user_email_max_length', '2018-08-16 15:08:18.776295'); args=['auth', '0003_alter_user_email_max_length', '2018-
08-16 15:08:18.776295']
  Applying auth.0003_alter_user_email_max_length... OK
(0.013) SHOW FULL TABLES; args=None
(0.164) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0004_alter_user_username_opts', '2018-08-16 15:08:18.970966'); args=['auth', '0004_alter_user_username_opts', '2018-08-16
15:08:18.970966']
  Applying auth.0004_alter_user_username_opts... OK
ALTER TABLE `auth_user` MODIFY `last_login` datetime(6) NULL; (params [])
(0.213) ALTER TABLE `auth_user` MODIFY `last_login` datetime(6) NULL; args=[]
(0.016) SHOW FULL TABLES; args=None
(0.206) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0005_alter_user_last_login_null', '2018-08-16 15:08:19.416542'); args=['auth', '0005_alter_user_last_login_null', '2018-08
-16 15:08:19.416542']
  Applying auth.0005_alter_user_last_login_null... OK
(0.022) SHOW FULL TABLES; args=None
(0.177) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0006_require_contenttypes_0002', '2018-08-16 15:08:19.696792'); args=['auth', '0006_require_contenttypes_0002', '2018-08-1
6 15:08:19.696792']
  Applying auth.0006_require_contenttypes_0002... OK
(0.014) SHOW FULL TABLES; args=None
(0.187) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0007_alter_validators_add_error_messages', '2018-08-16 15:08:19.934158'); args=['auth', '0007_alter_validators_add_error_m
essages', '2018-08-16 15:08:19.934158']
  Applying auth.0007_alter_validators_add_error_messages... OK
ALTER TABLE `auth_user` MODIFY `username` varchar(150) NOT NULL; (params [])
(0.195) ALTER TABLE `auth_user` MODIFY `username` varchar(150) NOT NULL; args=[]
(0.018) SHOW FULL TABLES; args=None
(0.153) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0008_alter_user_username_max_length', '2018-08-16 15:08:20.388736'); args=['auth', '0008_alter_user_username_max_length',
'2018-08-16 15:08:20.388736']
  Applying auth.0008_alter_user_username_max_length... OK
ALTER TABLE `auth_user` MODIFY `last_name` varchar(150) NOT NULL; (params [])
(0.187) ALTER TABLE `auth_user` MODIFY `last_name` varchar(150) NOT NULL; args=[]
(0.013) SHOW FULL TABLES; args=None
(0.132) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('auth', '0009_alter_user_last_name_max_length', '2018-08-16 15:08:20.790483'); args=['auth', '0009_alter_user_last_name_max_length'
, '2018-08-16 15:08:20.790483']
  Applying auth.0009_alter_user_last_name_max_length... OK
CREATE TABLE `django_session` (`session_key` varchar(40) NOT NULL PRIMARY KEY, `session_data` longtext NOT NULL, `expire_date` datetime(6) NOT NULL); (params None)
(0.152) CREATE TABLE `django_session` (`session_key` varchar(40) NOT NULL PRIMARY KEY, `session_data` longtext NOT NULL, `expire_date` datetime(6) NOT NULL); args=None
(0.163) SELECT engine FROM information_schema.tables WHERE table_name = 'django_session'; args=['django_session']
(0.161) SELECT engine FROM information_schema.tables WHERE table_name = 'django_session'; args=['django_session']
(0.186) SELECT engine FROM information_schema.tables WHERE table_name = 'django_session'; args=['django_session']
CREATE INDEX `django_session_expire_date_a5c62663` ON `django_session` (`expire_date`); (params ())
(0.189) CREATE INDEX `django_session_expire_date_a5c62663` ON `django_session` (`expire_date`); args=()
(0.013) SHOW FULL TABLES; args=None
(0.262) INSERT INTO `django_migrations` (`app`, `name`, `applied`) VALUES ('sessions', '0001_initial', '2018-08-16 15:08:21.836393'); args=['sessions', '0001_initial', '2018-08-16 15:08:21.836393']
  Applying sessions.0001_initial... OK
(0.013) SHOW FULL TABLES; args=None
(0.266) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.285) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'admin' AND `django_content_
type`.`model` = 'logentry'); args=('admin', 'logentry')
(0.309) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'admin' AND `django_content_
type`.`model` = 'logentry'); args=('admin', 'logentry')
(0.339) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('admin', 'logentry'); args=['admin', 'logentry']
(0.375) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
 WHERE `auth_permission`.`content_type_id` IN (1) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(1,)
(0.250) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add log entry', 1, 'add_logentry'), ('Can change log entry', 1, 'change_logentry'), ('Can delete log entry', 1, 'de
lete_logentry'), ('Can view log entry', 1, 'view_logentry'); args=('Can add log entry', 1, 'add_logentry', 'Can change log entry', 1, 'change_logentry', 'Can delete log entry', 1, 'delete_logentry', 'Can vi
ew log entry', 1, 'view_logentry')
(0.271) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`app_label` = 'admin'; args=('admin',)
(0.237) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'permission'); args=('auth', 'permission')
(0.353) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'permission'); args=('auth', 'permission')
(0.203) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('auth', 'permission'); args=['auth', 'permission']
(0.270) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'group'); args=('auth', 'group')
(0.278) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'group'); args=('auth', 'group')
(0.157) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('auth', 'group'); args=['auth', 'group']
(0.129) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'user'); args=('auth', 'user')
(0.136) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'auth' AND `django_content_t
ype`.`model` = 'user'); args=('auth', 'user')
(0.084) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('auth', 'user'); args=['auth', 'user']
(0.093) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
 WHERE `auth_permission`.`content_type_id` IN (2, 3, 4) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(2, 3, 4)
(0.137) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add permission', 2, 'add_permission'), ('Can change permission', 2, 'change_permission'), ('Can delete permission',
 2, 'delete_permission'), ('Can view permission', 2, 'view_permission'), ('Can add group', 3, 'add_group'), ('Can change group', 3, 'change_group'), ('Can delete group', 3, 'delete_group'), ('Can view group
', 3, 'view_group'), ('Can add user', 4, 'add_user'), ('Can change user', 4, 'change_user'), ('Can delete user', 4, 'delete_user'), ('Can view user', 4, 'view_user'); args=('Can add permission', 2, 'add_per
mission', 'Can change permission', 2, 'change_permission', 'Can delete permission', 2, 'delete_permission', 'Can view permission', 2, 'view_permission', 'Can add group', 3, 'add_group', 'Can change group',
3, 'change_group', 'Can delete group', 3, 'delete_group', 'Can view group', 3, 'view_group', 'Can add user', 4, 'add_user', 'Can change user', 4, 'change_user', 'Can delete user', 4, 'delete_user', 'Can vie
w user', 4, 'view_user')
(0.094) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`app_label` = 'auth'; args=('auth',)
(0.122) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'contenttypes' AND `django_c
ontent_type`.`model` = 'contenttype'); args=('contenttypes', 'contenttype')
(0.123) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'contenttypes' AND `django_c
ontent_type`.`model` = 'contenttype'); args=('contenttypes', 'contenttype')
(0.127) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('contenttypes', 'contenttype'); args=['contenttypes', 'contenttype']
(0.091) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
 WHERE `auth_permission`.`content_type_id` IN (5) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(5,)
(0.089) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add content type', 5, 'add_contenttype'), ('Can change content type', 5, 'change_contenttype'), ('Can delete conten
t type', 5, 'delete_contenttype'), ('Can view content type', 5, 'view_contenttype'); args=('Can add content type', 5, 'add_contenttype', 'Can change content type', 5, 'change_contenttype', 'Can delete conte
nt type', 5, 'delete_contenttype', 'Can view content type', 5, 'view_contenttype')
(0.100) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_content_type`.`app_label` = 'contenttypes'; args=('conten
ttypes',)
(0.093) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'sessions' AND `django_conte
nt_type`.`model` = 'session'); args=('sessions', 'session')
(0.122) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE (`django_content_type`.`app_label` = 'sessions' AND `django_conte
nt_type`.`model` = 'session'); args=('sessions', 'session')
(0.148) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('sessions', 'session'); args=['sessions', 'session']
(0.097) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permission`.`content_type_id` = `django_content_type`.`id`)
 WHERE `auth_permission`.`content_type_id` IN (6) ORDER BY `django_content_type`.`app_label` ASC, `django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(6,)
(0.132) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add session', 6, 'add_session'), ('Can change session', 6, 'change_session'), ('Can delete session', 6, 'delete_ses
sion'), ('Can view session', 6, 'view_session'); args=('Can add session', 6, 'add_session', 'Can change session', 6, 'change_session', 'Can delete session', 6, 'delete_session', 'Can view session', 6, 'view
_session')
(0.093) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `d
jango_content_type` WHERE `django_content_type`.`app_label` = 'sessions'; args=('sessions',)
(0.134) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `d
jango_content_type` WHERE (`django_content_type`.`app_label` = 'app01' AND `django_content_type`.`model` = 'book');
 args=('app01', 'book')
(0.144) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `d
jango_content_type` WHERE (`django_content_type`.`app_label` = 'app01' AND `django_content_type`.`model` = 'book');
 args=('app01', 'book')
(0.108) INSERT INTO `django_content_type` (`app_label`, `model`) VALUES ('app01', 'book'); args=['app01', 'book']
(0.109) SELECT `auth_permission`.`content_type_id`, `auth_permission`.`codename` FROM `auth_permission` INNER JOIN `django_content_type` ON (`auth_permi
ssion`.`content_type_id` = `django_content_type`.`id`) WHERE `auth_permission`.`content_type_id` IN (7) ORDER BY `django_content_type`.`app_label` ASC,
`django_content_type`.`model` ASC, `auth_permission`.`codename` ASC; args=(7,)
(0.093) INSERT INTO `auth_permission` (`name`, `content_type_id`, `codename`) VALUES ('Can add book', 7, 'add_book'), ('Can change book', 7, 'change_boo
k'), ('Can delete book', 7, 'delete_book'), ('Can view book', 7, 'view_book'); args=('Can add book', 7, 'add_book', 'Can change book', 7, 'change_book',
 'Can delete book', 7, 'delete_book', 'Can view book', 7, 'view_book')
(0.129) SELECT `django_content_type`.`id`, `django_content_type`.`app_label`, `django_content_type`.`model` FROM `django_content_type` WHERE `django_con
tent_type`.`app_label` = 'app01'; args=('app01',)

(venv) C:\Users\TQTL911\PycharmProjects\ORM>

39-單表操做之添加記錄

一、單表操做添加記錄的兩種方式;

view.py;

from django.shortcuts import render,HttpResponse


#from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
    #添加表記錄;
        #方式1:經過類生成對象的方法進行添加,可是須要使用save()方法進行保存記錄;
    # book_obj = Book(id=1,title="Python紅寶書",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    # book_obj.save()
    # return HttpResponse("OK")

        #方式2:create是有返回值的,就是當前生成的對象的記錄;
    book_obj = Book.objects.create(title="Python全棧開發指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    print(book_obj.title)
    print(book_obj.price)
    print(book_obj.publish)
    return HttpResponse("記錄添加成功!")

操做日誌:

"D:\Program\PyCharm 2018.1.4\bin\runnerw.exe" C:\Users\TQTL911\PycharmProjects\ORM\venv\Scripts\python.exe C:/Users/TQTL911/PycharmProjects/ORM/manage.py runserver 8000
Performing system checks...

System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
(0.010) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:42:21
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
Internal Server Error: /index/
Traceback (most recent call last):
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\app01\views.py", line 15, in index
    book_obj = Book.objects.create(ititle="Python紅寶書",price=100,pub_date="2018-08-16",publish="人民教育出版社")
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 411, in create
    obj = self.model(**kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 484, in __init__
    raise TypeError("'%s' is an invalid keyword argument for this function" % kwarg)
TypeError: 'ititle' is an invalid keyword argument for this function
[16/Aug/2018 23:42:35] "GET /index/ HTTP/1.1" 500 81556
Performing system checks...

System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
August 16, 2018 - 23:42:49
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.010) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python紅寶書', '2018-08-16', '100.00', '人民教育出版社'); args=['Python紅寶書', '2018-08-16', '100.00', '人民教育出版社']
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
Internal Server Error: /index/
Traceback (most recent call last):
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
    result = self._query(query)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
    conn.query(q)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
    result.read()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
    first_packet = self.connection._read_packet()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
    packet.check_error()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.IntegrityError: (1062, "Duplicate entry 'Python紅寶書' for key 'title'")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\app01\views.py", line 15, in index
    book_obj = Book.objects.create(title="Python紅寶書",price=100,pub_date="2018-08-16",publish="人民教育出版社")
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 413, in create
    obj.save(force_insert=True, using=self.db)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 717, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 747, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 830, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 868, in _do_insert
    using=using, raw=raw)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 1133, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1285, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
    result = self._query(query)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
    conn.query(q)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
    result.read()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
    first_packet = self.connection._read_packet()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
    packet.check_error()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Python紅寶書' for key 'title'")
[16/Aug/2018 23:42:53] "GET /index/ HTTP/1.1" 500 219064
Performing system checks...

System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.012) SHOW FULL TABLES; args=None
(0.012) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:43:28
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.009) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.009) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.009) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python全棧開發指南', '2018-08-16', '100.00', '人民教育出版社'); args=['Python全棧開發指南', '2018-08-16', '100.00', '人民教育出版社']
Python全棧開發指南
100
人民教育出版社
Internal Server Error: /index/
Traceback (most recent call last):
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 137, in _get_response
    "returned None instead." % (callback.__module__, view_name)
ValueError: The view app01.views.index didn't return an HttpResponse object. It returned None instead.
[16/Aug/2018 23:43:30] "GET /index/ HTTP/1.1" 500 58321
Performing system checks...

System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:44:05
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.012) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python全棧開發指南', '2018-08-16', '100.00', '人民教育出版社'); args=['Python全棧開發指南', '2018-08-16', '100.00', '人民教育出版社']
(0.012) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
(0.012) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
Internal Server Error: /index/
Traceback (most recent call last):
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
    result = self._query(query)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
    conn.query(q)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
    result.read()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
    first_packet = self.connection._read_packet()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
    packet.check_error()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
pymysql.err.IntegrityError: (1062, "Duplicate entry 'Python全棧開發指南' for key 'title'")

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\app01\views.py", line 15, in index
    book_obj = Book.objects.create(title="Python全棧開發指南",price=100,pub_date="2018-08-16",publish="人民教育出版社")
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 413, in create
    obj.save(force_insert=True, using=self.db)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 717, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 747, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 830, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\base.py", line 868, in _do_insert
    using=using, raw=raw)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\query.py", line 1133, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\models\sql\compiler.py", line 1285, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\django\db\backends\mysql\base.py", line 71, in execute
    return self.cursor.execute(query, args)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 170, in execute
    result = self._query(query)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\cursors.py", line 328, in _query
    conn.query(q)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 516, in query
    self._affected_rows = self._read_query_result(unbuffered=unbuffered)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 727, in _read_query_result
    result.read()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 1066, in read
    first_packet = self.connection._read_packet()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\connections.py", line 683, in _read_packet
    packet.check_error()
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\protocol.py", line 220, in check_error
    err.raise_mysql_exception(self._data)
  File "C:\Users\TQTL911\PycharmProjects\ORM\venv\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
    raise errorclass(errno, errval)
django.db.utils.IntegrityError: (1062, "Duplicate entry 'Python全棧開發指南' for key 'title'")
[16/Aug/2018 23:44:07] "GET /index/ HTTP/1.1" 500 219853
Performing system checks...

System check identified no issues (0 silenced).
(0.012) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.012) SHOW FULL TABLES; args=None
August 16, 2018 - 23:44:17
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.012) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Python全棧開發指南2', '2018-08-16', '100.00', '人民教育出版社'); args=['Python全棧開發指南2', '2018-08-16', '100.00', '人民教育出版社']
Python全棧開發指南2
100
人民教育出版社
[16/Aug/2018 23:44:19] "GET /index/ HTTP/1.1" 200 21
Performing system checks...

System check identified no issues (0 silenced).
(0.009) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.009) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
(0.010) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 16, 2018 - 23:45:46
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Performing system checks...

System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
August 16, 2018 - 23:46:50
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()

40-單表操做之查詢API

一、查詢API初識;

  先作查詢操做,由於沒有拿到查詢結果就不知道如何去刪除、修改,兩者理論上是基於查詢操做進行的;

  • all();
  • first()、last()基於all()方法基礎之上使用;
  • filter();
  • get();
<1> all():                  查詢全部結果

<2> filter(**kwargs):       它包含了與所給篩選條件相匹配的對象;

<3> get(**kwargs):          返回與所給篩選條件相匹配的對象,返回結果有且只有一個,
                            若是符合篩選條件的對象超過一個或者沒有都會拋出錯誤;

<4> exclude(**kwargs):      它包含了與所給篩選條件不匹配的對象;

<5> order_by(*field):       對查詢結果排序;

<6> reverse():              對查詢結果反向排序;

<8> count():                返回數據庫中匹配查詢(QuerySet)的對象數量;

<9> first():                返回第一條記錄;

<10> last():                返回最後一條記錄;

<11> exists():              若是QuerySet包含數據,就返回True,不然返回False;

<12> values(*field):        返回一個ValueQuerySet——一個特殊的QuerySet,運行後獲得的並非一系列;
                            model的實例化對象,而是一個可迭代的字典序列;
<13> values_list(*field):   它與values()很是類似,它返回的是一個元組序列,values返回的是一個字典序列;

<14> distinct():            從返回結果中剔除重複紀錄;

views.py;

from django.shortcuts import render,HttpResponse


#from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
    #----------------------添加表記錄;--------------------------#
        #方式1:經過類生成對象的方法進行添加,可是須要使用save方法進行保存記錄;
    # book_obj = Book(id=1,title="Python紅寶書",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    # book_obj.save()
    # return HttpResponse("OK")

        #方式2:create是有返回值的,就是當前生成的對象的記錄;
    # book_obj = Book.objects.create(title="Python全棧開發指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    # print(book_obj.title)
    # print(book_obj.price)
    # print(book_obj.publish)
    #return HttpResponse("記錄添加成功!")
    #----------------------查詢表記錄API--------------------------#
    ""
    """
    一、方法的返回值;
    二、方法的調用者;
    
    :param request: 
    :return: 
    """
    #(1)all查詢素有結果;
    book_list = Book.objects.all()
    print(book_list)#ook: Book object (1)>, <Book: Book object (3)>, <Book: Book object (5)>]>,相似於列表中,放着一個個對象![obj1,obj2,.....objn]
    for obj in book_list:
        print("書名-書的價格",obj.title,"-",obj.price)
    print('-'*20)
    print("book_list[1].title",book_list[1].title)
    print("book_list[1].price",book_list[1].price)

    #(2)first和last方法;調用者:queryset對象;返回值:model對象;
    book_first = Book.objects.all().first()
    book_last = Book.objects.all().last()
    print("book_first",book_first)
    print("book_last",book_last)
    #(3)filter()方法_返回值:queryset對象;
    #Book.objects.all().filter(title = "python")
    Book.objects.all().filter(price = 100)#[obj1,obj2,obj3]
    book_filter_first = Book.objects.filter(price=100).first()
    print("book_list",book_list)#<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>]>
    print("book_filter_first",book_filter_first)
    #(3) get()方法;有且只有一個查詢結果時候纔有意義,返回值:model對象;
    #book_get_title = Book.objects.get(title="go")
    book_get_price = Book.objects.get(price=200)
    #print("book_get_title",book_get_title)
    print("book_get_price",book_get_price)


    return HttpResponse("OK")

操做日誌:

app01.models.Book.MultipleObjectsReturned: get() returned more than one Book -- it returned 2!
[17/Aug/2018 10:48:42] "GET /index/ HTTP/1.1" 500 77130
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
書名-書的價格 Python紅寶書 - 100.00
書名-書的價格 Python全棧開發指南 - 100.00
書名-書的價格 Python全棧開發指南2 - 100.00
書名-書的價格 Go語言從入門到放棄 - 201.00
書名-書的價格 Go全棧開發 - 200.00
--------------------
book_list[1].title Python全棧開發指南
book_list[1].price 100.00
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`; args=()
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=()
book_first Python紅寶書
book_last Go全棧開發
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC  LIMIT 1; args=()
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=(Decimal('100'),)
book_list <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
book_filter_first Python紅寶書
(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 200; args=(Decimal('200'),)
[17/Aug/2018 10:49:06] "GET /index/ HTTP/1.1" 200 2
book_get_price Go全棧開發
Performing system checks...

System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 17, 2018 - 10:53:51
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

41-單表操做之查詢API-2

一、單表查詢API之其餘方法;

  • exclude();
  • order_by();
  • count();
  • exist();

views.py;

from django.shortcuts import render,HttpResponse


#from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
    #----------------------添加表記錄;--------------------------#
        #方式1:經過類生成對象的方法進行添加,可是須要使用save方法進行保存記錄;
    # book_obj = Book(id=1,title="Python紅寶書",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    # book_obj.save()
    # return HttpResponse("OK")

        #方式2:create是有返回值的,就是當前生成的對象的記錄;
    # book_obj = Book.objects.create(title="Python全棧開發指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    # print(book_obj.title)
    # print(book_obj.price)
    # print(book_obj.publish)
    #return HttpResponse("記錄添加成功!")
    #----------------------查詢表記錄API--------------------------#
    ""
    """
    一、方法的返回值;
    二、方法的調用者;
    
    :param request: 
    :return: 
    """
    #(1)all查詢素有結果;
    book_list = Book.objects.all()
    print(book_list)#ook: Book object (1)>, <Book: Book object (3)>, <Book: Book object (5)>]>,相似於列表中,放着一個個對象![obj1,obj2,.....objn]
    for obj in book_list:
        print("書名-書的價格",obj.title,"-",obj.price)
    print('-'*20)
    print("book_list[1].title",book_list[1].title)
    print("book_list[1].price",book_list[1].price)

    #(2)first和last方法;調用者:queryset對象;返回值:model對象;
    book_first = Book.objects.all().first()
    book_last = Book.objects.all().last()
    print("book_first",book_first)
    print("book_last",book_last)
    #(3)filter()方法,支持多條件過濾;——返回值:queryset對象;
    #Book.objects.all().filter(title = "python")
    Book.objects.all().filter(price = 100)#[obj1,obj2,obj3]
    book_filter_first = Book.objects.filter(price=100).first()
    book_filter_and = Book.objects.filter(price=100,title = "Go")
    print("book_list",book_list)#<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>]>
    print("book_filter_first",book_filter_first)
    print("book_filter_and",book_filter_and)
    #(3) get()方法;有且只有一個查詢結果時候纔有意義,返回值:model對象;
    #book_get_title = Book.objects.get(title="go")
    book_get_price = Book.objects.get(price=200)
    #print("book_get_title",book_get_title)
    print("book_get_price",book_get_price)

    #(5)exclude過濾取反;返回值:
    book_exclude = Book.objects.all().exclude(title="Go")
    print("book_exclude",book_exclude)#<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>


    #(6)order_by方法,調用者:queryset對象;返回值:queryset對象;
    book_order_by_id = Book.objects.all().order_by("-id")
    book_order_by_price = Book.objects.all().order_by("price")
    book_order_by_price_id = Book.objects.all().order_by("price","id")
    print("book_order_by_price",book_order_by_price)#ASC
    print("book_order_by_id",book_order_by_id)#DESC
    print("book_order_by_price_id",book_order_by_price_id)#DESC&ACS


    #count()方法——調用者:queryset對象,返回值:int;
    book_count = Book.objects.all().count()
    print(book_count)

    #exist()方法——返回值:布爾值,True 或者 False;
    book_all = Book.objects.all()#效率低下!
    book_exist = Book.objects.all().exists()#效率低下!
    print("book_all",book_all)
    print("book_exist",book_exist)#book_exist True


    return HttpResponse("OK")

操做日誌:

System check identified no issues (0 silenced).
(0.019) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
August 17, 2018 - 11:13:56
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
書名-書的價格 Python紅寶書 - 100.00
書名-書的價格 Python全棧開發指南 - 100.00
書名-書的價格 Python全棧開發指南2 - 100.00
書名-書的價格 Go語言從入門到放棄 - 201.00
書名-書的價格 Go全棧開發 - 200.00
--------------------
book_list[1].title Python全棧開發指南
book_list[1].price 100.00
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC  LIMIT 1; args=()
book_first Python紅寶書
book_last Go全棧開發
book_list <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=(Decimal('100'),)
book_filter_first Python紅寶書
book_filter_and <QuerySet []>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` = 100 AND `app01_book`.`title` = 'Go')  LIMIT 21; args=(Decimal('100'), 'Go')
book_get_price Go全棧開發
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 200; args=(Decimal('200'),)
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE NOT (`app01_book`.`title` = 'Go')  LIMIT 21; args=('Go',)
book_exclude <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
book_order_by_price <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go全棧開發>, <Book: Go語言從入門到放棄>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC  LIMIT 21; args=()
book_order_by_id <QuerySet [<Book: Go全棧開發>, <Book: Go語言從入門到放棄>, <Book: Python全棧開發指南2>, <Book: Python全棧開發指南>, <Book: Python紅寶書>]>
(0.019) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC  LIMIT 21; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC, `app01_book`.`id` ASC  LIMIT 21; args=()
book_order_by_price_id <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go全棧開發>, <Book: Go語言從入門到放棄>]>
5
(0.010) SELECT COUNT(*) AS `__count` FROM `app01_book`; args=()
(0.011) SELECT (1) AS `a` FROM `app01_book`  LIMIT 1; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
[17/Aug/2018 11:13:56] "GET /index/ HTTP/1.1" 200 2
book_all <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
book_exist True
Performing system checks...

System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 17, 2018 - 11:14:37
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

42-單表操做之查詢API-3

一、單表操做之查詢API;

  • values();
  • values_list();
  • distinct(),基於values()或者values_list()方法進行使用;

views.py;

from django.shortcuts import render,HttpResponse


#from app01 import models
from app01.models import Book
# Create your views here.
def index(request):
    #----------------------添加表記錄;--------------------------#
        #方式1:經過類生成對象的方法進行添加,可是須要使用save方法進行保存記錄;
    # book_obj = Book(id=1,title="Python紅寶書",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    # book_obj.save()
    # return HttpResponse("OK")

        #方式2:create是有返回值的,就是當前生成的對象的記錄;
    # book_obj = Book.objects.create(title="Python全棧開發指南2",price=100,pub_date="2018-08-16",publish="人民教育出版社")
    # print(book_obj.title)
    # print(book_obj.price)
    # print(book_obj.publish)
    #return HttpResponse("記錄添加成功!")
    #----------------------查詢表記錄API--------------------------#
    ""
    """
    一、方法的返回值;
    二、方法的調用者;
    
    :param request: 
    :return: 
    """
    #(1)、all查詢素有結果;
    book_list = Book.objects.all()
    print(book_list)#ook: Book object (1)>, <Book: Book object (3)>, <Book: Book object (5)>]>,相似於列表中,放着一個個對象![obj1,obj2,.....objn]
    for obj in book_list:
        print("書名-書的價格",obj.title,"-",obj.price)
    print('-'*20)
    print("book_list[1].title",book_list[1].title)
    print("book_list[1].price",book_list[1].price)

    #(2)、first和last方法;調用者:queryset對象;返回值:model對象;
    book_first = Book.objects.all().first()
    book_last = Book.objects.all().last()
    print("book_first",book_first)
    print("book_last",book_last)
    #(3)、filter()方法,支持多條件過濾;——返回值:queryset對象;
    #Book.objects.all().filter(title = "python")
    Book.objects.all().filter(price = 100)#[obj1,obj2,obj3]
    book_filter_first = Book.objects.filter(price=100).first()
    book_filter_and = Book.objects.filter(price=100,title = "Go")
    print("book_list",book_list)#<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>]>
    print("book_filter_first",book_filter_first)
    print("book_filter_and",book_filter_and)
    #(4) 、get()方法;有且只有一個查詢結果時候纔有意義,返回值:model對象;
    #book_get_title = Book.objects.get(title="go")
    book_get_price = Book.objects.get(price=200)
    #print("book_get_title",book_get_title)
    print("book_get_price",book_get_price)

    #(5)、exclude過濾取反;返回值:
    book_exclude = Book.objects.all().exclude(title="Go")
    print("book_exclude",book_exclude)#<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>


    #(6)、order_by方法,調用者:queryset對象;返回值:queryset對象;
    book_order_by_id = Book.objects.all().order_by("-id")
    book_order_by_price = Book.objects.all().order_by("price")
    book_order_by_price_id = Book.objects.all().order_by("price","id")
    print("book_order_by_price",book_order_by_price)#ASC
    print("book_order_by_id",book_order_by_id)#DESC
    print("book_order_by_price_id",book_order_by_price_id)#DESC&ACS


    #(7)、count()方法——調用者:queryset對象,返回值:int;
    book_count = Book.objects.all().count()
    print(book_count)

    #(8)、exist()方法——返回值:布爾值,True 或者 False
    book_all = Book.objects.all()#效率低下!
    book_exist = Book.objects.all().exists()#效率低下!
    print("book_all",book_all)
    print("book_exist",book_exist)#book_exist True
    #(9)、values()方法;返回值是1個列表內部嵌套字典;
    #book_values = Book.objects.values()
    #book_values = Book.objects.all().values("price","title")
    book_values = Book.objects.all().values()
    print("book_values",book_values)#book_values <QuerySet [{'id': 1, 'title': 'Python紅寶書', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 3, 'title': 'Python全棧開發指南', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 5, 'title': 'Python全棧開發指南2', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 7, 'title': 'Go語言從入門到放棄', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('201.00'), 'publish': '清華出版社'}, {'id': 8, 'title': 'Go全棧開發', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('200.00'), 'publish': '北大出版社'}]>
    #print(book_values.get('price'))
    #(11)、values_list()方法;返回值是元組;
    book_values_list = Book.objects.all().values_list("price","title")
    print("book_values_list",book_values_list)#book_values_list <QuerySet [(Decimal('100.00'), 'Python紅寶書'), (Decimal('100.00'), 'Python全棧開發指南'), (Decimal('100.00'), 'Python全棧開發指南2'), (Decimal('201.00'), 'Go語言從入門到放棄'), (Decimal('200.00'), 'Go全棧開發')]>


    #(11)、distinct()方法:配合values()和values_list()方法使用;

    book_distinct_values = Book.objects.all().values("price").distinct()
    book_distinct_values_list = Book.objects.all().values_list("price").distinct()
    print("book_distinct_values",book_distinct_values)
    print("book_distinct_values_list",book_distinct_values_list)
    """
    book_distinct_values <QuerySet [{'price': Decimal('100.00')}, {'price': Decimal('201.00')}, {'price': Decimal('200.00')}]>
    book_distinct_values_list <QuerySet [(Decimal('100.00'),), (Decimal('201.00'),), (Decimal('200.00'),)]>
    """
    return HttpResponse("OK")

操做日誌:

System check identified no issues (0 silenced).
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.019) SHOW FULL TABLES; args=None
August 17, 2018 - 11:34:40
(0.012) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
<QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`; args=()
書名-書的價格 Python紅寶書 - 100.00
書名-書的價格 Python全棧開發指南 - 100.00
書名-書的價格 Python全棧開發指南2 - 100.00
書名-書的價格 Go語言從入門到放棄 - 201.00
書名-書的價格 Go全棧開發 - 200.00
--------------------
book_list[1].title Python全棧開發指南
book_list[1].price 100.00
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=()
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC  LIMIT 1; args=()
book_first Python紅寶書
book_last Go全棧開發
book_list <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
book_filter_first Python紅寶書
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=(Decimal('100'),)
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` = 100 AND `app01_book`.`title` = 'Go')  LIMIT 21; args=(Decimal('100'), 'Go')
book_filter_and <QuerySet []>
book_get_price Go全棧開發
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 200; args=(Decimal('200'),)
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE NOT (`app01_book`.`title` = 'Go')  LIMIT 21; args=('Go',)
book_exclude <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
book_order_by_price <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go全棧開發>, <Book: Go語言從入門到放棄>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC  LIMIT 21; args=()
book_order_by_id <QuerySet [<Book: Go全棧開發>, <Book: Go語言從入門到放棄>, <Book: Python全棧開發指南2>, <Book: Python全棧開發指南>, <Book: Python紅寶書>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`id` DESC  LIMIT 21; args=()
book_order_by_price_id <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go全棧開發>, <Book: Go語言從入門到放棄>]>
(0.012) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` ORDER BY `app01_book`.`price` ASC, `app01_book`.`id` ASC  LIMIT 21; args=()
5
(0.010) SELECT COUNT(*) AS `__count` FROM `app01_book`; args=()
(0.010) SELECT (1) AS `a` FROM `app01_book`  LIMIT 1; args=()
book_all <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go語言從入門到放棄>, <Book: Go全棧開發>]>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
book_exist True
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book`  LIMIT 21; args=()
book_values <QuerySet [{'id': 1, 'title': 'Python紅寶書', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 3, 'title': 'Python全棧開發指南', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 5, 'title': 'Python全棧開發指南2', 'pub_date': datetime.date(2018, 8, 16), 'price': Decimal('100.00'), 'publish': '人民教育出版社'}, {'id': 7, 'title': 'Go語言從入門到放棄', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('201.00'), 'publish': '清華出版社'}, {'id': 8, 'title': 'Go全棧開發', 'pub_date': datetime.date(2018, 8, 17), 'price': Decimal('200.00'), 'publish': '北大出版社'}]>
(0.011) SELECT `app01_book`.`price`, `app01_book`.`title` FROM `app01_book`  LIMIT 21; args=()
book_values_list <QuerySet [(Decimal('100.00'), 'Python紅寶書'), (Decimal('100.00'), 'Python全棧開發指南'), (Decimal('100.00'), 'Python全棧開發指南2'), (Decimal('201.00'), 'Go語言從入門到放棄'), (Decimal('200.00'), 'Go全棧開發')]>
(0.011) SELECT DISTINCT `app01_book`.`price` FROM `app01_book`  LIMIT 21; args=()
book_distinct_values <QuerySet [{'price': Decimal('100.00')}, {'price': Decimal('201.00')}, {'price': Decimal('200.00')}]>
book_distinct_values_list <QuerySet [(Decimal('100.00'),), (Decimal('201.00'),), (Decimal('200.00'),)]>
(0.019) SELECT DISTINCT `app01_book`.`price` FROM `app01_book`  LIMIT 21; args=()
[17/Aug/2018 11:34:41] "GET /index/ HTTP/1.1" 200 2
Performing system checks...

System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.019) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.011) SHOW FULL TABLES; args=None
(0.011) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
August 17, 2018 - 11:35:06
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

43-單表操做之模糊查詢

一、單表查詢之模糊查詢-基於雙下劃線;

Book.objects.filter(price__in=[100,200,300])
Book.objects.filter(price__gt=100)
Book.objects.filter(price__lt=100)
Book.objects.filter(price__range=[100,200])
Book.objects.filter(title__contains="python")
Book.objects.filter(title__icontains="python")
Book.objects.filter(title__startswith="py")
Book.objects.filter(pub_date__year=2012)

views.py;

    #--------------------查詢表記錄之模糊查詢--------------------------#
    #大於
    book_gt_lt = Book.objects.filter(price__gt =10,price__lt = 200)
    print(book_gt_lt)

    book_price_in = Book.objects.all(price__in =[200,100])
    print(book_price_in)
    book_startwith = Book.objects.filter(title__startswith="p")
    print(book_startwith)

    book_contains = Book.objects.filter(title__contains="h")
    print(book_contains)

    book_endwith = Book.objects.filter(title__icontains="H")
    print(book_endwith)

操做日誌:

book_gt_lt <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>]>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` > 10 AND `app01_book`.`price` < 200)  LIMIT 21; args=(Decimal('10'), Decimal('200'))
book_price_in <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>, <Book: Go全棧開發>]>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` IN (200, 100)  LIMIT 21; args=(Decimal('200'), Decimal('100'))
(0.008) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE BINARY 'p%'  LIMIT 21; args=('p%',)
book_startwith <QuerySet []>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE BINARY '%h%'  LIMIT 21; args=('%h%',)
book_contains <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>]>
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE '%H%'  LIMIT 21; args=('%H%',)
book_endwith <QuerySet [<Book: Python紅寶書>, <Book: Python全棧開發指南>, <Book: Python全棧開發指南2>]>
[17/Aug/2018 12:04:29] "GET /index/ HTTP/1.1" 200 2

44-單表查詢之刪除與修改操做

一、單表查詢之刪除與修改;

  • delete()方法;
  • update()方法;

view.py;

# --------------------查詢表記錄之刪除、修改記錄--------------------------#
    #(1)、delete()方法,刪除記錄;
    book_delete = Book.objects.filter(price=201).delete()
    print("book_delete",book_delete)#(0.010) DELETE FROM `app01_book` WHERE `app01_book`.`price` = 201; args=(Decimal('201'),)

    book_delete_first = Book.objects.filter(price=100).first().delete()
    print("book_delete_first",book_delete_first)
    #(2)update()方法,修改記錄;
    book_update = Book.objects.filter(title="PHP1").update(title = "《細說PHP 崔曉昭》")
    print("book_update",book_update)
    #新增記錄;
    book_obj = Book.objects.create(title="PHP4",price=101,pub_date="2018-08-17",publish="人民教育出版社1")
    book_obj = Book.objects.create(title="Ruby4",price=101,pub_date="2018-08-17",publish="人民教育出版社1")
    book_obj = Book.objects.create(title="R4",price=101,pub_date="2018-08-17",publish="人民教育出版社1")
    """
    (0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE '%H%'  LIMIT 21; args=('%H%',)
    (0.010) DELETE FROM `app01_book` WHERE `app01_book`.`price` = 201; args=(Decimal('201'),)
    book_delete (0, {'app01.Book': 0})
    (0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=(Decimal('100'),)
    (0.009) DELETE FROM `app01_book` WHERE `app01_book`.`id` IN (5); args=(5,)
    book_delete_first (1, {'app01.Book': 1})
    (0.010) UPDATE `app01_book` SET `title` = '《細說PHP 崔曉昭》' WHERE `app01_book`.`title` = 'PHP1'; args=('《細說PHP 崔曉昭》', 'PHP1')
    book_update 0
    (0.019) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('PHP4', '2018-08-17', '101.00', '人民教育出版社1'); args=['PHP4', '2018-08-17', '101.00', '人民教育出版社1']
    (0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Ruby4', '2018-08-17', '101.00', '人民教育出版社1'); args=['Ruby4', '2018-08-17', '101.00', '人民教育出版社1']
    (0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('R4', '2018-08-17', '101.00', '人民教育出版社1'); args=['R4', '2018-08-17', '101.00', '人民教育出版社1']
    R4
    [17/Aug/2018 12:16:14] "GET /index/ HTTP/1.1" 200 2
    """
    print(book_obj.title)

操做日誌:

(0.010) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`title` LIKE '%H%'  LIMIT 21; args=('%H%',)
(0.010) DELETE FROM `app01_book` WHERE `app01_book`.`price` = 201; args=(Decimal('201'),)
book_delete (0, {'app01.Book': 0})
(0.009) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` = 100 ORDER BY `app01_book`.`id` ASC  LIMIT 1; args=(Decimal('100'),)
(0.009) DELETE FROM `app01_book` WHERE `app01_book`.`id` IN (5); args=(5,)
book_delete_first (1, {'app01.Book': 1})
(0.010) UPDATE `app01_book` SET `title` = '《細說PHP 崔曉昭》' WHERE `app01_book`.`title` = 'PHP1'; args=('《細說PHP 崔曉昭》', 'PHP1')
book_update 0
(0.019) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('PHP4', '2018-08-17', '101.00', '人民教育出版社1'); args=['PHP4', '2018-08-17', '101.00', '人民教育出版社1']
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('Ruby4', '2018-08-17', '101.00', '人民教育出版社1'); args=['Ruby4', '2018-08-17', '101.00', '人民教育出版社1']
(0.010) INSERT INTO `app01_book` (`title`, `pub_date`, `price`, `publish`) VALUES ('R4', '2018-08-17', '101.00', '人民教育出版社1'); args=['R4', '2018-08-17', '101.00', '人民教育出版社1']
R4
[17/Aug/2018 12:16:14] "GET /index/ HTTP/1.1" 200 2

45-單表操做章節做業

一、查詢老男孩出版社過的價格大於200的書籍;

二、查詢2017年8月出版的全部以py開頭的書籍的名稱;

三、查詢價格爲50,100或150的全部書籍名稱及其出版社名稱;

四、查詢價格在100到200之間的全部書籍的名稱及其價格;

五、查詢全部人民出版社的書籍的價格,(從高到低排序、去重);

46-單表操做章節做業講解

一、查詢老男孩出版社過的價格大於200的書籍;

二、查詢2017年8月出版的全部以py開頭的書籍的名稱;

三、查詢價格爲50,100或150的全部書籍名稱及其出版社名稱;

四、查詢價格在100到200之間的全部書籍的名稱及其價格;

五、查詢全部人民出版社的書籍的價格,(從高到低排序、去重);

views.py;

from django.shortcuts import render,HttpResponse


#from app01 import models
from app01.models import Book
# Create your views here.
"""
一、查詢老男孩出版社過的價格大於200的書籍;
二、查詢2017年8月出版的全部以py開頭的書籍的名稱;
三、查詢價格爲50,100或150的全部書籍名稱及其出版社名稱;
四、查詢價格在100到200之間的全部書籍的名稱及其價格;
五、查詢全部人民出版社的書籍的價格,(從高到低排序、去重);
"""

def query(request):
    book_01 = Book.objects.filter(price__gt=200,publish = "人民教育出版社1")
    print("一、查詢老男孩出版社過的價格大於200的書籍;",book_01)



    book_02 = Book.objects.filter(title__istartswith="py",pub_date__year = 2018,pub_date__month=8)
    print("二、查詢2017年8月出版的全部以py開頭的書籍的名稱;",book_02)


    book_03 = Book.objects.all().filter(price__in=[50,100,150]).values("title","publish")
    print("三、查詢價格爲50,100或150的全部書籍名稱及其出版社名稱;",book_03)



    book_04 = Book.objects.all().filter(price__range=[100,200]).values("title","price")
    print("四、查詢價格在100到200之間的全部書籍的名稱及其價格;",book_04)

    book_05 = Book.objects.all().filter(publish="人民教育出版社1").values("price").distinct().order_by("price")
    print("五、查詢全部人民出版社的書籍的價格,(從高到低排序、去重);",book_05)

    return HttpResponse("Query OK")

操做日誌:

System check identified no issues (0 silenced).
(0.010) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.010) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
(0.010) SHOW FULL TABLES; args=None
August 18, 2018 - 10:31:09
Django version 2.1, using settings 'ORM.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
(0.019) SELECT `django_migrations`.`app`, `django_migrations`.`name` FROM `django_migrations`; args=()
(0.011) SELECT @@SQL_AUTO_IS_NULL; args=None
(0.011) SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED; args=None
一、查詢老男孩出版社過的價格大於200的書籍; <QuerySet []>
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (`app01_book`.`price` > 200 AND `app01_book`.`publish` = '人民教育出版社1')  LIMIT 21; args=(Decimal('200'), '人民教育出版社1')
(0.011) SELECT `app01_book`.`id`, `app01_book`.`title`, `app01_book`.`pub_date`, `app01_book`.`price`, `app01_book`.`publish` FROM `app01_book` WHERE (EXTRACT(MONTH FROM `app01_book`.`pub_date`) = 8 AND `app01_book`.`pub_date` BETWEEN '2018-01-01' AND '2018-12-31' AND `app01_book`.`title` LIKE 'py%')  LIMIT 21; args=(8, '2018-01-01', '2018-12-31', 'py%')
二、查詢2017年8月出版的全部以py開頭的書籍的名稱; <QuerySet [<Book: python>, <Book: Python全棧開發與實戰>]>
(0.011) SELECT `app01_book`.`title`, `app01_book`.`publish` FROM `app01_book` WHERE `app01_book`.`price` IN (50, 100, 150)  LIMIT 21; args=(Decimal('50'), Decimal('100'), Decimal('150'))
三、查詢價格爲50,100或150的全部書籍名稱及其出版社名稱; <QuerySet [{'title': 'PHP2', 'publish': '人民教育出版社1'}, {'title': 'R3', 'publish': '人民教育出版社1'}, {'title': 'Ruby4', 'publish': '人民教育出版社1'}]>
四、查詢價格在100到200之間的全部書籍的名稱及其價格; <QuerySet [{'title': 'Go全棧開發', 'price': Decimal('200.00')}, {'title': 'Ruby', 'price': Decimal('101.00')}, {'title': 'R', 'price': Decimal('101.00')}, {'title': 'python', 'price': Decimal('101.00')}, {'title': 'R1', 'price': Decimal('101.00')}, {'title': 'R3', 'price': Decimal('150.00')}, {'title': 'Python全棧開發與實戰', 'price': Decimal('101.00')}, {'title': 'Ruby4', 'price': Decimal('100.00')}, {'title': 'R4', 'price': Decimal('101.00')}]>
(0.011) SELECT `app01_book`.`title`, `app01_book`.`price` FROM `app01_book` WHERE `app01_book`.`price` BETWEEN 100 AND 200  LIMIT 21; args=(Decimal('100'), Decimal('200'))
(0.011) SELECT DISTINCT `app01_book`.`price` FROM `app01_book` WHERE `app01_book`.`publish` = '人民教育出版社1' ORDER BY `app01_book`.`price` ASC  LIMIT 21; args=('人民教育出版社1',)
[18/Aug/2018 10:31:52] "GET /query/ HTTP/1.1" 200 8
五、查詢全部人民出版社的書籍的價格,(從高到低排序、去重); <QuerySet [{'price': Decimal('50.00')}, {'price': Decimal('88.00')}, {'price': Decimal('99.00')}, {'price': Decimal('100.00')}, {'price': Decimal('101.00')}, {'price': Decimal('150.00')}]>

47-圖書管理系統之添加頁面

一、新建項目bookms並建立應用文件app01;

二、檢查settings.py文件;

三、導入app01下的views模塊並配置urls.py,新增"addbook/";

from django.contrib import admin
from django.urls import path

from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('addbook/', views.addbook),
]

四、編寫views.py業務邏輯代碼;

from django.shortcuts import render,HttpResponse

# Create your views here.

from app01.models import Book
def addbook(request):
    if request.method == "POST":
        title = request.POST.get("title")
        price = request.POST.get("price")
        date = request.POST.get("date")
        publish = request.POST.get("publish")

        book_obj = Book.objects.create(title=title,price=price,pub_date=date,publish=publish)
        return HttpResponse("OK")

    return render(request,"addbook.html")

五、編寫addbook.html頁面並引入css文件;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

{#    <link rel="stylesheet" href="/app01/static/bootstrap-3.3.7-dist/css/bootstrap.css">#}
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <style>
        .container{
            margin-top: 100px;
        }
        .btn{
            margin-top: 10px;
        }
    </style>
</head>
<body>

<h3>添加書籍</h3>

<div class="container">
     <div class="row">
         <div class="col-md-6 col-md-offset-3">
             <form action="" method="post">
                 {% csrf_token %}
                 <div>
                     <label for="">書籍名稱</label>
                     <input type="text" class="form-control" name="title">
                 </div>
                 <div>
                     <label for="">價格</label>
                     <input type="text" class="form-control" name="price">
                 </div>
                 <div>
                     <label for="">出版日期</label>
                     <input type="date" class="form-control" name="date">
                 </div>
                 <div>
                     <label for="">出版社</label>
                     <input type="text" class="form-control" name="publish">
                 </div>

                 <input type="submit" class="btn btn-success pull-right">


             </form>
         </div>
     </div>
</div>



</body>
</html>

六、編寫models.py數據庫文件;

from django.db import models

# Create your models here.
class Book(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=32)
    pub_date = models.DateField()
    price = models.DecimalField(max_digits=8,decimal_places=2)
    publish = models.CharField(max_length=32)

七、執行遷移數據庫操做並啓動Django項目進行訪問;

python manage.py makemigrations

python manage.py migrate

八、查看Django框架中自帶的sqllite3數據庫的數據;

九、經過Pycharm IDE工具自帶的數據庫鏈接工具,進行數據查看;

1) 初次使用,使用Pycharm下載sqllite驅動程序;

2)尋找本地db.sqllite3文件,進行鏈接驗證;

C:\Users\TQTL911\PycharmProjects\bookms\db.sqlite3

3)初識jdbc數據庫鏈接;

jdbc:sqlite:C:\Users\TQTL911\PycharmProjects\bookms\db.sqlite3

4)使用Test Connection按鈕,進行測試鏈接;

48-圖書管理系統之查看書籍

一、新增urls.py中的path路徑;

"""book URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('addbook/', views.addbook),
    path('books/', views.books),
]

二、編輯views.py下的業務邏輯代碼;

from django.shortcuts import render,HttpResponse

# Create your views here.

from app01.models import Book
def addbook(request):
    if request.method == "POST":
        title = request.POST.get("title")
        price = request.POST.get("price")
        date = request.POST.get("date")
        publish = request.POST.get("publish")
        book_obj = Book.objects.create(title=title,price=price,pub_date=date,publish=publish)
        return HttpResponse("addbook is OK")
    return render(request,"addbook.html")

def books(request):
    book_list = Book.objects.all()#
    return render(request,"books.html",locals())

三、編輯前端books.html頁面代碼;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

{#    <link rel="stylesheet" href="/bookms/app01/static/bootstrap-3.3.7-dist/">#}
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <style>
        .container{
            margin-top: 100px;
        }
        .btn{
            margin-top: 10px;
        }
    </style>
</head>
<body>

<h3>查看書籍</h3>

<div class="container">
     <div class="row">
         <div class="col-md-6 col-md-offset-3">
             <table class="table table-striped table-bordered">
                 <thead>
                 <tr>
                     <th>書籍名稱</th>
                     <th>價格</th>
                     <th>出版日期</th>
                     <th>出版社</th>
                     <th>刪除操做</th>
                     <th>編輯出版社</th>
                 </tr>
                 </thead>
                 <tbody>
                    {% for book in book_list %}
                 <tr>
                     <td>{{ book.title }}</td>
                     <td>{{ book.price }}</td>
                     <td>{{ book.pub_date|date:'Y-m-d' }}</td>
                     <td>{{ book.publish }}</td>
                     <td><a href="" class="btn btn-danger">刪除</a></td>
                     <td><a href="" class="btn btn-info">編輯</a></td>
                 </tr>
                 {% endfor %}
                 </tbody>
             </table>
         </div>
     </div>
</div>



</body>
</html>

四、進行查看頁面展現效果;

49-圖書管理系統之刪除數據

一、urls.py中新增re_path路徑;

from django.contrib import admin
from django.urls import path,re_path

from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('addbook/', views.addbook),
    path('books/', views.books),
    re_path(r'books/(\d+)/delete',views.delbook),#delbook(request,x)
]

二、views.py視圖函數中添加delbook功能代碼;

from django.shortcuts import render,HttpResponse,redirect
# Create your views here.

from app01.models import Book
def addbook(request):
    if request.method == "POST":

        title = request.POST.get("title")
        price = request.POST.get("price")
        pub_date = request.POST.get("date")
        publish = request.POST.get("publish")
        book_obj = Book.objects.create(title=title,price=price,pub_date=pub_date,publish=publish)
        return redirect("/addbook/")
    return render(request,"addbook.html")

def books(request):
    book_list = Book.objects.all()
    return render(request,"books.html",locals())

def delbook(request,id):
    Book.objects.filter(id=id).delete()
    return redirect("/books/")

三、books.html中分別添加一個刪除、編輯按鈕;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

{#    <link rel="stylesheet" href="/bookms/app01/static/bootstrap-3.3.7-dist/">#}
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <style>
        .container{
            margin-top: 100px;
        }
        .btn{
            margin-top: 10px;
        }
    </style>
</head>
<body>

<h3>查看書籍</h3>

<div class="container">
     <div class="row">
         <div class="col-md-6 col-md-offset-3">
             <a href="/addbook" class="btn btn-primary">添加書籍</a>
             <table class="table table-striped table-bordered">
                 <thead>
                 <tr>
                     <th>書籍名稱</th>
                     <th>價格</th>
                     <th>出版日期</th>
                     <th>出版社</th>
                     <th>刪除操做</th>
                     <th>編輯出版社</th>
                 </tr>
                 </thead>
                 <tbody>
                    {% for book in book_list %}
                 <tr>
                     <td>{{ book.title }}</td>
                     <td>{{ book.price }}</td>
                     <td>{{ book.pub_date|date:'Y-m-d' }}</td>
                     <td>{{ book.publish }}</td>
                     <td><a href="/books/{{ book.pk }}/delete" class="btn btn-danger">刪除</a></td>
                     <td><a href="" class="btn btn-info">編輯</a></td>
                 </tr>
                 {% endfor %}
                 </tbody>
             </table>
         </div>
     </div>
</div>

</body>
</html>

四、添加或刪除後經過redirect()方法,重定向至某個頁面;

  • return redirect("/addbook/")
  • return redirect("/books/")

五、檢查頁面重定向跳轉以及頁面按鈕是否可見;

50-圖書管理系統之編輯功能

一、urls.py中新增re_path路徑;

"""book URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,re_path

from app01 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('addbook/', views.addbook),
    path('books/', views.books),
    re_path(r'books/(\d+)/delete',views.delbook),#delbook(request,x)
    re_path(r'books/(\d+)/modify',views.modbooks),#modbook(request,x)
]

二、views.py視圖函數中添加modbooks功能代碼;

from django.shortcuts import render,HttpResponse,redirect
# Create your views here.

from app01.models import Book
def addbook(request):
    if request.method == "POST":

        title = request.POST.get("title")
        price = request.POST.get("price")
        pub_date = request.POST.get("date")
        publish = request.POST.get("publish")
        book_obj = Book.objects.create(title=title,price=price,pub_date=pub_date,publish=publish)
        return redirect("/addbook/")
    return render(request,"addbook.html")


def books(request):
    book_list = Book.objects.all()
    return render(request,"books.html",locals())

def delbook(request,id):
    Book.objects.filter(id=id).delete()
    return redirect("/books/")

def modbooks(request,id):
    book_obj = Book.objects.filter(id=id).first()
    if request.method == "POST":
        title = request.POST.get("title")
        price = request.POST.get("price")
        pub_date = request.POST.get("date")
        publish = request.POST.get("publish")
        book_obj = Book.objects.filter(id=id).update(title=title, price=price, pub_date=pub_date, publish=publish)
        return redirect("/books/")
    return render(request, "modbooks.html", {"book_obj":book_obj})

三、modbooks.html中分別添加一個刪除、編輯按鈕;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
{#    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">#}
    <style>
        .container{
            margin-top: 100px;
        }
        .btn{
            margin-top: 10px;
        }
    </style>
</head>
<body>

<h3>編輯書籍</h3>

<div class="container">
     <div class="row">
         <div class="col-md-6 col-md-offset-3">
             <form action="" method="post">
                 {% csrf_token %}
                 <div>
                     <label for="">書籍名稱</label>
                     <input type="text" class="form-control" name="title" value="{{ book_obj.title }}">
                 </div>
                 <div>
                     <label for="">價格</label>
                     <input type="text" class="form-control" name="price" value="{{ book_obj.price }}">
                 </div>
                 <div>
                     <label for="">出版日期</label>
                     <input type="date" class="form-control" name="date" value="{{ book_obj.pub_date|date:"Y-m-d" }}">
                 </div>
                 <div>
                     <label for="">出版社</label>
                     <input type="text" class="form-control" name="publish" value="{{ book_obj.publish }}">
                 </div>
                 <input type="submit" class="btn btn-success pull-right">


             </form>
         </div>
     </div>
</div>

</body>
</html>

四、修改後經過redirect()方法,重定向至books頁面;

  • return redirect("/books/")
  • return render(request, "modbooks.html", {"book_obj":book_obj})

五、檢查頁面重定向跳轉以及頁面按鈕是否可見;

相關文章
相關標籤/搜索