2

I have the following tree structure:

Cat 1
--Sub Cat 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?

Hanpan
  • 10,013
  • 25
  • 77
  • 115
  • Are you sure that there's one query per parent? The whole point of MPTT is that queries like this are cheap. `get_ancestors`, in particular, is one single query. Can you check (perhaps in the shell, by looking at `connection.queries`) that `get_absolute_url` is the culprit? – Daniel Roseman Jul 01 '11 at 13:24

1 Answers1

0

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!

Bernhard Vallant
  • 49,468
  • 20
  • 120
  • 148
  • Yes, something like this perhas: http://stackoverflow.com/questions/8283031/how-do-i-add-a-trailing-slash-for-django-mptt-based-categorization-app – Jonatan Littke May 07 '12 at 10:26