Django版本差異
阿新 • • 發佈:2022-03-02
Django版本差異
url和path
Django1.x路由層使用的是url方法
Django2.x和Django3.x版本中路由層使用的是path方法
url()第一個引數支援正則
path() 第一個引數是不支援正則,寫什麼就匹配什麼。
2.x和3.x還支援re_path,相當於1.x中的url,第一個引數支援正則,不過不推薦
path中的轉換器
雖然path不支援正則,但是他的內部支援五種轉換器
str,匹配除了路徑分隔符(/)之外的非空字串,這是預設的形式 int,匹配正整數,包含0。 slug,匹配字母、數字以及橫槓、下劃線組成的字串。 uuid,匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00。 path,匹配任何非空字串,包含了路徑分隔符(/)(不能用?)
例子
path('articles/<int:year>/<int:month>/<slug:other>/', views.article_detail) # 針對路徑http://127.0.0.1:8000/articles/2009/123/hello/,path會匹配出引數year=2009,month=123,other='hello'傳遞給函式article_detail
自定義轉換器
除了有預設的五個轉換器之外,還支援自定義轉換器
1、在app01下新建檔案path_ converters.py,檔名可以隨意命名
class MonthConverter: regex='\d{2}' # 屬性名必須為regex def to_python(self, value): return int(value) def to_url(self, value): return value # 匹配的regex是兩個數字,返回的結果也必須是兩個數字
2、在urls.py中,使用register_converter
將其註冊到URL配置中:
from django.urls import path,register_converter from app01.path_converts import MonthConverter register_converter(MonthConverter,'mon') from app01 import views urlpatterns = [ path('articles/<int:year>/<mon:month>/<slug:other>/', views.article_detail, name='aaa'), ]
3、views.py中的檢視函式article_detail
from django.shortcuts import render,HttpResponse,reverse def article_detail(request,year,month,other): print(year,type(year)) print(month,type(month)) print(other,type(other)) print(reverse('xxx',args=(1988,12,'hello'))) # 反向解析結果/articles/1988/12/hello/ return HttpResponse('xxxx')
4、測試
# 1、在瀏覽器輸入http://127.0.0.1:8000/articles/2009/12/hello/,path會成功匹配出引數year=2009,month=12,other='hello'傳遞給函式article_detail # 2、在瀏覽器輸入http://127.0.0.1:8000/articles/2009/123/hello/,path會匹配失敗,因為我們自定義的轉換器mon只匹配兩位數字,而對應位置的123超過了2位
模型層裡面1.x外來鍵預設都是級聯更新刪除的,但是到了2.x和3.x中需要你自己動手配置引數