路由匹配的区别
Django 1.x 版本
from django.urls import url
urlpatterns = [
url(r'^admin/', admin.site.urls),
]
Django 2.x 与 3.x 版本
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
第一个参数不是正则,写的什么参数,就按照什么参数来匹配!
解决方法:导入一个新的模块re_path
即可
from django.urls import re_path
urlpatterns = [
re_path(r'^admin/', admin.site.urls),
]
转换器
Django 2.x 与 3.x 版本 path
还支持转换器功能
针对路径
http://127.0.0.1:8000/articles/2009/123/hello/
,path会匹配出参数year=2009,month=123,other='hello’传递给函数article_detail
urlpatterns = [
path('articles/<int:year>/<int:month>/<slug:other>/', views.article_detail),
]
五种默认的转换器(相当于一个有名分组,自动帮你转换成指定类型的数据)
<str:xxx>
: 默认的类型,匹配非空字符串,不包含路径分隔符/
<int:xxx>
:匹配非负整数
<slug:xxx>
:匹配字母、数字已经横杠-
、下划线_
组成的字符串
<uuid:xxx>
:**匹配格式化的 UUID **
<path:xxx>
:匹配任何非空字符串,包含路径分隔符/
,不能用?
针对月份month,转换器int是无法精准匹配的,如果我们只想匹配两个字符,那么转换器slug也无法满足需求,针对等等这一系列复杂的需要,我们可以定义自己的转化器。转化器是一个类或接口,它的要求有三点:
regex
类属性,字符串类型to_python(self, value)
方法,value是由类属性regex
所匹配到的字符串,返回具体的Python变量值,以供Django传递到对应的视图函数中。to_url(self, value)
方法,和to_python
相反,value是一个具体的Python变量值,返回其字符串,通常用于url反向引用。
自定义转换器示例:
-
在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是两个数字,返回的结果也必须是两个数字
-
在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'), ]
-
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')
-
测试
# 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位
# 模型层的区别
models.py
中创建外键,会有区别
Django 1.x 版本 :创建外键默认就是级联更新,级联删除
Django 2.x 与 3.x 版本:需要自己指定 字段