Saturday, June 3, 2017

Re: Django URL dispacher

On Saturday 03 June 2017 13:57:54 Domagoj KovaÄ wrote:

 

> url(r'^(?P<article_category_slug>[\w-]+)/$',

> views.view_article_category, name="article-category"),

>

> url(r'^(?P<product_category_slug>[\w-]+)/$',

> views.view_product_category, name="product-category"),

>

>

> Lets say that i have a article_category called news and product

> category call books.

>

> When user requests for /news - first route is matched, request is

> successfully resolved and that's ok.

> When user requests for /books - first route is matched but books

> doesn't exist in article_category table and some kind of error is

> raised.

>

> Is there any way to do something like this, when request is not

> resolved on first matched url (like in the second example), continue

> matching until request is successfully resolved.

>

> i have two solution but non of those solution i don't like.

>

> 1. just add products prefix to product-category url

 

And what's not to like? It's clear to humans and has SEO value.

 

> 2. use only one route in urlconfig:

>

> url(r'^(?P<category_slug>[\w-]+)/$', views.view_category_resolver,

> name="category"),

>

> and then in my view i would implement some kind of routing logic - i

> would say this is better solution for me because i would like to have

> my urls as simple as possible.

 

So an article titled 'coffee' and a product category 'coffee' end up with the same URL. And don't think it won't happen. I've seen it many times, especially with products that don't have a plural, like "fish". The theory being that if you name categories plular and products singular, you won't clash.

 

But yes, you would need to do this in a view or .... create your own resolver (see django.urls.resolvers).

 

Also think about the fact that just to resolve your URL, you would need at minimum n database queries, where n is the number of models matching. That don't scale well.

--

Melvyn Sopacua

No comments:

Post a Comment