Search code examples
djangodjango-mpttmptt

Django MPTT - how to query based on URL segments


I have:

Home
    Things with Fur
        Dog
        Horse
    Basket Ball Games
        Twenty One
        Horse

Assuming the slug for each is title.lower().replace(' ', '-'), my URLs would be:

/home/
    /home/things-with-fur/
        /home/things-with-fur/dog/
        /home/things-with-fur/horse/
    /home/basket-ball-games/
        /home/basket-ball-games/twenty-one/
        /home/basket-ball-games/horse/

The slug field is unique_together with the parent.

I need to, based on the URL segements, query for the correct category. I can't simply query for the basket ball game horse with Category.objects.get(mptt_level=2, slug=u'horse'), because there happens to be a category with the slug horse under a different category, but at the same level. So, how am I supposed to query for my horse category correctly without climbing up the chain and checking each level?


Solution

  • Store the full path to each item in the database.