Categories, Subcategories, and Subcategories of Zhango

I have a simple model model:

class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self', blank = True, null = True, related_name="children") 

At first, my data seemed to need only categories and subcategories, but I realized that there are some cases where I still want to subcategorize.

I want my urls to be a category / subcategory / subcategory

I was thinking about how to implement this, but I'm not sure, since the correspondence of my url template looks like this:

 url(r'^business/(?P<parent>[-\w]+)/(?P<category_name>[-\w]+)$', 'directory.views.show_category'), 

Basically, only one subcategory is allowed, since my view method accepts these two parameters.

What is the best way to handle this?

+4
source share
1 answer

How about unlimited levels? On urls.py page:

 url(r'^business/(?P<hierarchy>.+)/', 'directory.views.show_category') 

And in the /views.py directory:

 def show_category(request, hierarchy): category_slugs = hierarchy.split('/') categories = [] for slug in category_slugs: if not categories: parent = None else: parent = categories[-1] category = get_object_or_404(Category, slug=slug, parent=parent) categories.append(category) ... 

Remember to add unique_together = ('slug', 'parent',) to Category.Meta, otherwise you are doomed.

[update]

Can I just query db with category_slugs [-1], and if the resulting category has no children, we know its leaf category, otherwise we know that it has subcategories, and we show them? - alexBrand

@alexBrand: consider the following hypothetical URLs:

 /business/manufacture/frozen/pizza/ /business/restaurant/italian/pizza/ /business/delivery-only/italian/pizza/ /business/sports/eating-contest/pizza/ 

If you think that such a scenario is possible, then IMHO a simpler test (without the entire hierarchy) is not enough.

What is your real problem regarding the proposed solution? At the end of the loop, the category of variables will contain the correct category_slugs[-1] , and you will get the entire hierarchy available in the categories . Do not worry about performance, my best advice is: do not try to optimize an elegant solution before profiling (you will be surprised).

+12
source

Source: https://habr.com/ru/post/1398934/


All Articles