Mer*_*ürk 3 python django django-urls
假设我们正在使用 django 实现一个简单的博客,并且可以通过 等 URL 访问博客文章/posts/1/。/posts/2/
当我们在 urlpatterns 数组中定义路径变量时,使用
path('post/<int:pk>/', ..., ...)和 之间的主要区别是什么path('post/<pk>/', ..., ...)?
这只是好的做法吗?有实际好处吗?
这只是好的做法吗?有实际好处吗?
是的。它使路径更加具体,并允许编写没有重叠模式的其他路径。
该int:部分是路径转换器[Django-doc]。如果未指定路径转换器,str则将使用路径转换器。
它指定将使用的正则表达式。例如,IntConverter[GitHub]有正则表达式:
Run Code Online (Sandbox Code Playgroud)class IntConverter: regex = '[0-9]+' def to_python(self, value): return int(value) def to_url(self, value): return str(value)
Run Code Online (Sandbox Code Playgroud)class StringConverter: regex = '[^/]+' def to_python(self, value): return value def to_url(self, value): return value
因此,这些是替换路径中的<int:pk>或 的正则表达式。<str:pk>如果你这样简单地写<pk>,那么它也会火起来post/foobar。你本身并不想要这个。例如,如果您稍后有另一条路径:
path('post/<int:pk>/', some_view),
path('post/new/', other_view),Run Code Online (Sandbox Code Playgroud)
如果您要编写<pk>,那么post/new路径也会触发some_view视图,而不是other_view,因为str:路径转换器也与 匹配new。