Django 是 Python 的 Web 框架,用於建立 Web 應用程式,避免其他框架中發現的安裝和依賴問題,例如 Flask 中很多外掛需要自己安裝。
Django 基於 MVT(模型檢視模板)架構,圍繞 CRUD(建立、檢索、更新、刪除)操作。CRUD 可以最好地解釋為構建 Django Web 應用程式的一種方法。
一般來說,CRUD 意味著對資料庫中的表執行建立、檢索、更新和刪除操作。
CRUD是什麼?
Create:
在資料庫的表中建立或新增新條目。
Retrieve:
以列表形式讀取、檢索、搜尋或檢視現有條目(列表檢視)或詳細檢索特定條目(詳細檢視) 。
Update:
更新或編輯資料庫表中的現有條目 。
Delete:
刪除、停用或刪除資料庫中表中的現有條目。
新建 models 應用
進入檔案根目錄執行命令建立應用,模型名稱必須是英文。建議用自己看得懂的或者通用的名字建立。比如說文章 model 定義 Article ,使用者 model 定義成 User 等等,是根據產品設計進行的定義。
新建專案&配置
cd TCM_ManageMentpython manage。py startapp 你的模型名稱
將建立好的模型資料夾移動到apps目錄下,並在settings。py中新增你新建的模型名稱
INSTALLED_APPS = [ #。。。 ‘你的模型名稱’, #。。。]
models。py 配置
from django。db import modelsclass People(models。Model): name = models。CharField(max_length = 8) character = models。CharField(max_length = 8) age = models。IntegerField() update_time = models。DataTimeField(auto_noww_add=True,null=True) def __str__(self): return self。name
資料遷移
python manage。py makemigrationspython manage。py migrate
Django ORM CURD
在學習 Django 的 CURD 之前先要了解一下什麼是 Django ORM。因為 CURD 是基於 Django 框架中對資料庫進行操作,那麼在 Django 中引入了 ORM 的概念(ORM:Object Relational Mapping 物件關係對映,是使用面向物件的思維來操作資料庫)
Python類名對應資料庫中的表名。
Python類屬性對應資料庫裡的欄位。
Python類例項對應資料庫表裡的具體的一行資料。
Django 的 ORM 操作可以實現 SQL 中操作資料庫命令相同的效果。
Create 新增
方法1:模型類管理器增加資料。
from django。http import HttpResponsefrom 。models import *def add_people(request): people = People(name=‘曹操’,character=‘孟德’,age=60) people。save()return HttpResponse(“成功新建資料!”)
方法2:模型類建立物件來進行增加。
from django。http import HttpResponsefrom 。models import *def add_people(request): people = People() people。name = ‘曹操’ people。character = ‘孟德’ people。age = 60 people。save()return HttpResponse(“成功新建資料!”)
方法3:檢查資料是否存在,如果沒有相同資料即新增資料。
from django。http import HttpResponsefrom 。models import *def add_people(request): # 這裡結果返回 True 自動新增。 People。objects。get_or_create(name=‘曹操’,character=‘孟德’,age=60)return HttpResponse(“成功新建資料!”)
Retrieve 讀取
方法1:全部資料查詢。
from django。http import HttpResponsefrom 。models import *def filter_people(request): data = People。objects。all() print(data)return HttpResponse(“成功查詢資料!”)
方法2:獲取單個數據物件,不滿足條件會報錯。
from django。http import HttpResponsefrom 。models import *def filter_people(request): data = People。objects。get(name=“曹操”) data = People。objects。first() # 首條資料 data = People。objects。last() # 尾部資料 print(data)return HttpResponse(“成功查詢資料!”)
方法3:過濾資料,結果為滿足條件1個或者多個。
from django。http import HttpResponsefrom 。models import *def filter_people(request): # 過濾滿足條件 data = People。objects。filter(name=“曹操”) # 排除滿足條件 data = People。objects。exclude(name=“曹操”) # 按照欄位排序 data = People。objects。exclude(“name”) # 正序排列 data = People。objects。exclude(“-name”) # 倒序排列 # 反轉結果 data = People。objects。exclude(“name”)。reverse() # 倒序排列 data = People。objects。exclude(“-name”)reverse() # 正序排列 # 查詢指定列欄位的值 data = People。objects。values(“name”,“age”) # 查詢全部欄位的值 data = People。objects。values_list() # 對指定欄位進行去重 data = People。objects。distinct(“age”) print(data)return HttpResponse(“成功查詢資料!”)
方法4:判斷結果查詢資料是否存在。
from django。http import HttpResponsefrom 。models import *def filter_people(request): bool_= People。objects。filter(name=“曹操”)。exists() print(bool_) return HttpResponse(“成功查詢資料!”)
方法5:查詢資料的總行數。
from django。http import HttpResponsefrom 。models import *def filter_people(request): data = People。objects。all()。count() print(data) return HttpResponse(“成功查詢資料!”)
Update 更新
方法1:查詢定位資料,進行賦值修改。
from django。http import HttpResponsefrom 。models import Userdef update_people(request): data= People。objects。get(name=“曹操”) data。age=‘61’ data。save() return HttpResponse(“修改資料成功!”)
方法2:查詢批次修改。
from django。http import HttpResponsefrom 。models import Userdef update_people(request): User。objects。filter(name=‘曹操’)。update(name=‘caocao’) User。objects。all()。update(age=50) return HttpResponse(“修改資料成功!”)
Delete 刪除
方法1:透過例項直接進行資料刪除。
from django。http import HttpResponsefrom 。models import *def delete_people(request): People。objects。get(id=1)。delete() People。objects。filter(age=60)。delete() People。objects。all()。delete() return HttpResponse(“成功刪除資料!”)
方法2:透過 QuerySet 物件進行資料刪除。
from django。http import HttpResponsefrom 。models import *def delete_people(request): s = People。objects。filter(age=60) s[0]。delete() return HttpResponse(“成功刪除資料!”)
ORM 資料查詢條件拓展
對 Django ORM 操作與 SQL 操作進行對比演示,在 Django 環境下可以透過查詢結果的 QuerySet 使用下面的命令獲取 SQL 命令。
print(QuerySet。query)
exact & iexact
exact 完全匹配運算子,等價於 SQL 中使用 = 進行查詢,是 Django 的預設查詢條件。
iexact 完全匹配運算子,不區分大小寫,等價於 SQL 中 LIKE 無 % 匹配。
People。objects。get(id=1)People。objects。get(id__exact=1)People。objects。get(name__iexact=“曹操”)
等價於 SQL 中
SELECT * FROM people WHERE id = 1SELECT * FROM people WHERE name Like ‘曹操’
contains & icontains
contains 模糊匹配運算子,等價於 SQL 中 LIKE %xx% 匹配。
icontains 模糊匹配運算子,不區分大小寫,等價於 SQL 中 LIKE %xx% 匹配。
People。objects。filter(name__contains=“曹”)
等價於 SQL 中
SELECT * FROM people WHERE name Like ‘%曹操%’
in
提取給定的field的值是否在給定的容器(list、tuple或者任何一個可迭代的物件)中。
People。objects。filter(id__in=[1,2,3,4,5,6])
等價於 SQL 中
SELECT * FROM people WHERE id IN [1,2,3,4,5,6]
gt & gte & lt & lte
gt :對應SQL中的大於:“>”
gte :對應SQL中的大於等於:“>=”
lt :對應SQL中的小於:“<”
lte:對應SQL中的小於等於:“<=”
People。objects。filter(age__gt=60) # 年齡大於60People。objects。filter(age__gte=60) # 年齡大於等於60People。objects。filter(age__lt=60) # 年齡小於60People。objects。filter(age__lte=60) # 年齡小於等於60
等價於 SQL 中
SELECT * FROM people WHERE age > 60SELECT * FROM people WHERE age >= 60SELECT * FROM people WHERE age < 60SELECT * FROM people WHERE age <= 60
startswith & istartswith
startswith 欄位以給定值開始,區分大小寫,等價於 SQL 中 LIKE xx% 匹配。
istartswith 欄位以給定值開始,不區分大小寫,等價於 SQL 中 LIKE xx% 匹配。
People。objects。filter(name__startswith=“曹”) People。objects。filter(name__istartswith=“曹”)
等價於 SQL 中
SELECT * FROM people WHERE name LIKE ‘%曹’
endswith & iendswith
startswith 欄位以給定值結束,區分大小寫,等價於 SQL 中 LIKE %xx 匹配。
istartswith 欄位以給定值結束,不區分大小寫,等價於 SQL 中 LIKE %xx 匹配。
People。objects。filter(name__endswith=“曹”) People。objects。filter(name__iendswith=“曹”)
等價於 SQL 中
SELECT * FROM people WHERE name LIKE ‘曹%’
range
用於指定一個時間段,並查詢該時間段內的資料。
from datetime import datetimeStartTime = datetime。strptime(“2022-07-01 00:00:00”,‘%Y-%m-%d %H:%M:%S’)EndTime = datetime。strptime(“2022-07-10 00:00:00”,‘%Y-%m-%d %H:%M:%S’)People。objects。filter(update_time__range=(StartTime,EndTime))
等價於 SQL 中
SELECT * FROM people WHERE update_time BETWEEN ‘2022-07-01 00:00:00。000000’ AND ‘2022-07-10 00:00:00。000000’
date & time & year
用於直接在表單中過濾日期型別、時間型別、年份欄位。也可以配合 gt & gte & lt & lte 使用。
from datetime import date,timeStartDate = date(2022,7,01)EndTDate = date(2022,7,10)People。objects。filter(update_time__date=date(2022,7,5)) People。objects。filter(update_time__date__gt=date(2022,7,5)) People。objects。filter(update_time__date__range=(StartDate,EndTDate)) StartTime = time(0,0,0)EndTime = time(23,59,59)People。objects。filter(update_time__time=time(12,12,12)) People。objects。filter(update_time__time__gt=time(12,12,12)) People。objects。filter(update_time__time__range=(StartTime,EndTime)) StartYear = 2020EndYear = 2022People。objects。filter(update_time__year=2022) People。objects。filter(update_time__year__gt=2021) People。objects。filter(update_time__year__range=(StartYear,EndYear))
以Date舉例等價於 SQL 中
SELECT * FROM people WHERE DATE(update_time) > ‘2022-07-05’SELECT * FROM people WHERE DATE(update_time) = ‘2022-07-05’SELECT * FROM people WHERE DATE(update_time) BETWEEN ‘2022-07-01’ AND ‘2022-07-10’
isnull
SQL 語句中的 IS NULL 和 IS NOT NULL,接受引數 True 和 False 。
People。objects。filter(name__isnull=True) People。objects。filter(name__isnull=False)
等價於 SQL 中
SELECT * FROM people WHERE name IS NULLSELECT * FROM people WHERE name IS NOT NULL
regex & iregex
regex 根據指定的正則表示式來查詢,區分大小寫。
iregex 根據指定的正則表示式來查詢,不區分大小寫。
People。objects。filter(name__regex =“^曹”)
等價於 SQL 中
SELECT * FROM people WHERE name REGEX ‘^曹’
其他補充欄位
month 根據月份來查詢,同year。
day 根據日期來查詢,同year。
hour 根據小時來查詢,同year。
minute 根據分鐘來查詢,同year。
second 根據秒數來查詢,同year。
week_day 根據周幾來查詢,週日用1表示、週六用7表示,2-6代表週一到週五。