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).