我和一些老的Django代碼和url
功能時,不會在任何地方使用,類似的例子在the Django 1.4 documentation:爲什麼在Django 1.5文檔中經常使用url函數?
from django.conf.urls import patterns, url, include
urlpatterns = patterns('',
(r'^articles/2003/$', 'news.views.special_case_2003'),
(r'^articles/(\d{4})/$', 'news.views.year_archive'),
(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
,但我注意到the Django 1.5 documentation的url
功能經常被用到:
from django.conf.urls import patterns, url
urlpatterns = patterns('',
url(r'^articles/2003/$', 'news.views.special_case_2003'),
url(r'^articles/(\d{4})/$', 'news.views.year_archive'),
url(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'),
url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'),
)
這是爲什麼?這是一個慣例,還是有技術上的理由來使用url
函數?我將來應該遵循哪種做法,以及如何在不調用url
調用的情況下維護我的遺留代碼?
我沒有答案,但試圖從Django 1.5應用程序中刪除'url'並且它拋出一個錯誤。所以這可能不只是一個約定,它必須是必要的 – romainberger 2013-04-23 21:58:04
@romainberger Django 1.5教程不使用它:https://docs.djangoproject.com/en/1.5/intro/overview/,文檔中提到的元組是精細。您的錯誤必須存在於其他地方,或者教程已過時。 – millimoose 2013-04-23 22:02:35
技術原因是您可以在函數中使用命名參數,這在元組的大多數成員是可選的時很方便。我的猜測是'url()'只是爲可選元素添加了理智的默認值並返回一個元組。 (看到你設置了一個Django環境,你可以很容易地直接嘗試在REPL中調用'url()'。) – millimoose 2013-04-23 22:10:09