django urls optimization
urls with 2 request params:
/prefix1/1/
/prefix2/2/ /prefix1/1/prefix2/2 /p开发者_如何学Gorefix2/2/prefix1/1url( ur'^prefix1/(?P<p1>\d+)/$', 'app.views.view' ),
url( ur'^prefix2/(?P<p2>\d+)/$', 'app.views.view' ),
url( ur'^prefix1/(?P<p1>\d+)/prefix2/(?P<p2>\d+)/$', 'app.views.view' ),
url( ur'^prefix2/(?P<p2>\d+)/prefix1/(?P<p1>\d+)/$', 'app.views.view' ),
Is possible to do this more 'DRY' (with 3 request params, lines in urls.py
= 15) ?
I hacked together a sample and, if lazerscience's comment doesn't do it for you, here's what I came up with:
url(r'^(?P<param1>foo|bar)(/(?P<param2>\d+))?(/(?P<param3>\d+))?(/(?P<param4>\d+))?/$', 'demo.views.view'),
And my view looked like:
def view(request, *args, **kwargs):
return render_to_response("index.html",
{ 'dict': [(k, v) for k,v in kwargs.iteritems()] },
context_instance=RequestContext(request))
It progressively added parameters as you added to the url, left to right, just as you'd expect.
精彩评论