Django版本差異
# 一、路由層
'''
django 1.x路由層使用url方法
django 2.x/3.x路由層使用path方法 可以根據習慣使用re_path
path方法支持5種轉換器
'''
from django.urls import path,re_path
from app01 import views
urlpatterns = [
path('articles/<int:year>/', views.year_archive),
'''<int:year>相當于一個有名分組,其中int是django提供的轉換器,相當于正則表達式,專門用于匹配數字類型,而year則是我們為有名分組命的名,并且int會將匹配成功的結果轉換成整型后按照格式(year=整型值)傳給函數year_archive
'''
path('articles/<int:article_id>/detail/', views.detail_view),
path('articles/<int:article_id>/edit/', views.edit_view),
path('articles/<int:article_id>/delete/', views.delete_view),
]
'''
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'''
# 除了默認的5個轉換器,還提供了自定義轉換器類 eg:
# 自定義轉換器
class MonthConverter:
regex='\d{2}' # 屬性名必須為regex
def to_python(self, value):
return int(value)
def to_url(self, value):
return value # 匹配的regex是兩個數字,返回的結果也必須是兩個數字
# 在urls.py注冊轉換器
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'),
]
'''
Registering custom path converters?
For more complex matching requirements, you can define your own path converters.
A converter is a class that includes the following:
A regex class attribute, as a string.
A to_python(self, value) method, which handles converting the matched string into the type that should be passed to the view function. It should raise ValueError if it can’t convert the given value. A ValueError is interpreted as no match and as a consequence a 404 response is sent to the user unless another URL pattern matches.
A to_url(self, value) method, which handles converting the Python type into a string to be used in the URL. It should raise ValueError if it can’t convert the given value. A ValueError is interpreted as no match and as a consequence reverse() will raise NoReverseMatch unless another URL pattern matches.
For example:
class FourDigitYearConverter:
regex = '[0-9]{4}'
def to_python(self, value):
return int(value)
def to_url(self, value):
return '%04d' % value
Register custom converter classes in your URLconf using register_converter():
from django.urls import path, register_converter
from . import converters, views
register_converter(converters.FourDigitYearConverter, 'yyyy')
urlpatterns = [
path('articles/2003/', views.special_case_2003),
path('articles/<yyyy:year>/', views.year_archive),
...
]
'''
# 二、模型層
# 1.x外鍵默認級聯刪除、級聯更新,但2.x/3.x需要自己手動配置參數
# 1.x
models.ForeignKey(to='Publish')
# 2.x/3.x
models.ForeignKey(to='Publish',on_delete=models.CASCADE(),on_update=models.CASCADE())
非詳盡