Regex django url中命名组的动态数目
我想开发一个带有动态URL的web服务 带有命名组的通用url模式如下所示:Regex django url中命名组的动态数目,regex,django,url-pattern,Regex,Django,Url Pattern,我想开发一个带有动态URL的web服务 带有命名组的通用url模式如下所示: (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive') (r'^(?P<cat1>)/(?P<cat2>)/$', 'module.views.function') (r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive')
(r'^(?P<cat1>)/(?P<cat2>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/(?P<cat4>)/$', 'module.views.function')
(r'^articles/(?P\d{4})/(?P\d{2})/$,'news.views.month_archive')
出于我的目的,我需要更具活力,因为我从一开始就不知道组的数量
例如,可能的URL可以是:
- 文章/帖子/评论
- 文章/文章/作者
- 文章/职位/
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive')
(r'^(?P<cat1>)/(?P<cat2>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/$', 'module.views.function')
(r'^(?P<cat1>)/(?P<cat2>)/(?P<cat3>)/(?P<cat4>)/$', 'module.views.function')
(r'^(?P)/(?P)/$,“module.views.function”)
(r’^(?P)/(?P)/(?P)/$,“模块.视图.函数”)
(r'^(?P)/(?P)/(?P)/(?P)/$”,“module.views.function”)
。。
等等有没有更聪明的方法?提前谢谢 等待如果您只有一篇文章,那么您希望它是
article/post/
,否则您希望它是articles/post/
由于URL只是正则表达式,您可以执行以下操作
(r'^articles?/post/$', 'some_view')
?
测试s
中的0或1
但从根本上说,你的URL似乎没有意义,当你写文章/文章/评论时,听起来你想在所有的文章上发表评论?与article/post/
相同,这是什么意思?你想发哪篇文章(你只有一篇,最多一篇)
通常URL看起来像articles/5/post/comments
,这意味着“我想在pk为5的文章上发表评论”
如果我的回答没有帮助,我很抱歉。我想我没有真正理解你的问题。这让我感兴趣,我以前一直想要它,但从来没有想出一个好的解决方案。对不起,我的示例URL有误导性。问题更一般,不是关于文章或帖子,而是关于如果斜杠(命名组)的数量事先未知,如何在斜杠之间提取信息。您是否尝试过(r'(?P\w+)
(注意缺少的^
和$
)?但我不确定视图是否可以获取匹配的命名正则表达式组的列表。如果不起作用,请尝试(r'^(?)$)
(匹配整个URL)并拆分匹配/
。