开发者

Django MPTT - absolute url for category

I have the following tree structure:

Cat 1
--Sub Cat 开发者_StackOverflow中文版1
--Sub Cat 2
Cat 2
--Sub Cat 1
--Sub Cat 2
----Subsub Cat 1

Using django-mptt I'm able to display this information using 1 query which is great, but when trying to create a url like:

http://www.somesite.com/categories/cat1/subcat1/subsubcat1/

It is doing a SQL lookup for each of the categories in my tree to get the parent nodes slug (which is understandable.) Here is my code:

@models.permalink
    def get_absolute_url(self):
        if not getattr(self, '_slug', None):
            url = self.slug
            for ancestor in self.get_ancestors(ascending=True):
                url = url + ancestor.slug + u'/'
            self._slug = url    
        return ('catalogue_category', [str(self._slug)])

Is there any functionality of MPTT that will allow me to create a url slug without going crazy on the SQL?


I think the answer to your question is no. As Daniel already points out in his comment it should be able to get all ancestors with one query, but I agree that eg. you have a list of categories you will need to hit the database for each item once. If that's a problem for your project you could think about caching the instance's slugs somewhere and update them on the post_save signal of your Category model to fit the new slugs / titles!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜