I have a simple category 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 sub-sub-categorize.
I want my urls to be category/subcategory/sub-subcategory
I was thinking about how to implement this but I am not sure, since my url pattern matching looks like this:
url(r'^business/(?P<parent>[-\w]+)/(?P<category_name>[-\w]+)$', 'directory.views.show_category'),
Basically only allowing a single sub-category, since my view method accepts these two parameters.
What is the best way to handle this?
What about unlimited levels? At urls.py:
And at directory/views.py:
Don’t forget to add
unique_together = ('slug', 'parent',)to Category.Meta, otherwise you are doomed.[update]
@alexBrand: consider the following hypothetical URLs:
If you think such scenario is possible, then IMHO a simpler test (without the whole hierarchy) is not enough.
What are your real concerns regarding the proposed solution? At the end of the loop, the variable category will hold the correct
category_slugs[-1], and you will have the whole hierarchy available incategories. Don’t worry about performance, my best advice is: don’t try to optimize an elegant solution before profiling (you will be surprised).