具有多个URL匹配的Django URL配置 [英] Django url config with multiple urls matching

查看:45
本文介绍了具有多个URL匹配的Django URL配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的Django应用程序之一中,我们为视图定义了多个URL.

in one of our Django applications we have defined multiple urls for views.

第一个URL将通用特征与pk匹配,第二个匹配组.第二个URL与一个与pk匹配的子功能.

The first URL matches a general feature with pk and a second match group. The second URL matches a subfeature with pk.

在这两个url之间定义了更多url,因此很难一次看到它们.或者,例如,子功能将具有自己的url.py.

Between this two urls more urls are defined, so it is not easy to see them all at once. Or, for example, the subfeature would have its own url.py.

# old urls.py
url(r'^(?P<pk>\d+)/', views.b),
url(r'^subfeature/', views.a),

一段时间后,pk中也允许使用字母,因此我们现在必须将 \ d + 更改为 [^/] + .

After some time letters are also allowed in pk, so we now have to change \d+ to [^/]+.

# new urls.py
url(r'^(?P<pk>[^/]+)/', views.b),
url(r'^subfeature/', views.a),

现在该子功能已中断,因为该网址未正确匹配,在第一个网址中,子功能"与 pk 匹配.

Now the subfeature breaks because the url is not correctly matched, 'subfeature' is matched as pk in the first url.

如何在更改网址正则表达式时避免破坏其他网址?

How to avoid breaking other urls when changing a url regex?

推荐答案

我的建议是,您应该将类​​似的命名原理用作RESTful接口,因此不要将原始PK单独公开为URL.

My advice would be that you should apply similar naming principles as a RESTful interface and so never expose the raw PK alone as a URL.

相反,您应该始终提供某种命名空间,以使您的URL引用清楚.例如:

Instead, you should always provide some sort of namespace to make it clear what your URL is referencing. For example:

# new urls.py
url(r'^feature/(?P<pk>[^/]+)/', views.b),
url(r'^subfeature/', views.a),

这不仅解决了您的问题,而且还防止了多个表PK之间潜在的混淆,并使将来扩展变得更加容易.顺便说一句,它也符合 django文档.

Not only does this solve your problem, but it also prevents potential confusion between multiple table PKs and makes it much easier to extend in the future. Incidentally, it is also in line with the django docs.

只要您也可以控制GUI,这应该是一个容易的更改.但是,如果必须保留您现有的URL ,则其他答案更为合适.

This should be an easy change as long as you have control over the GUI too. However, if your existing URL must be retained, the other answers are more appropriate.

这篇关于具有多个URL匹配的Django URL配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆