I'm trying to include optional URL patterns in my Django project by adapting the multiple-routes pattern explained in this SO post.
In my urls.py file I have the following patterns.
urlpatterns = [
url(r'^(?P<slug>[-\w]+)\/?$', View.as_view()),
url(r'^(?P<section>[-\w]+)\/(?P<slug>[-\w]+)\/?$', View.as_view()),
url(r'^(?P<section>[-\w]+)\/(?P<tag>[-\w]+)\/(?P<slug>[-\w]+)\/?$',View.as_view()),
]
The parameters section, tag, and slug correspond to model fields. So a HTTP request to /foo/bar/baz returns a model instance with a "foo" section, "bar" tag, and "baz" slug. Not all model instances have a section or tag, those parameters are optional.
If you think about the URL dispatcher as a function with a domain of URLs and a codomain of model instances, the pattern I'm using isn't an injective function. /baz, /foo/baz, and /foo/bar/baz return the same model instance, but only the last URL should return the model instance.
In short, how do I configure my urlpatterns to return my foo-bar-baz model if, and only if, the requested URL is /foo/bar/baz?