2

I have a category tree and i'd like to get all products that are in the category tree. MPTT's documentation indicates that it only has methods that you can call to get objects.

I'm wondering how i can get it to work with related objects, for example, this syntax would ideal:

Product.objects.get(Q(category__ancestors=my_category)|Q(category=my_category))

Is there anything like this in django-mptt?

jpic
  • 32,891
  • 5
  • 112
  • 113
leech
  • 8,293
  • 7
  • 62
  • 78

1 Answers1

2

Try nesting the get_descendants() queryset in the product queryset:

Product.objects.get(category__in=my_category.get_descendants(include_self=True))

That should be the same than doing:

Product.objects.get(category__pk__in=my_category.get_descendants(include_self=True).values_list('pk'))
jpic
  • 32,891
  • 5
  • 112
  • 113
  • "Not sure i like the subquery" I really wonder what you mean. Thanks for your feedback and don't forget to [close the question](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – jpic Mar 23 '12 at 08:09
  • As i understand it, if you put a query like `my_category.get_descendants()` in another query, it will make a subquery. – leech Mar 23 '12 at 15:23
  • Exactly, what don't you like about it ? I find it super convenient ! – jpic Mar 23 '12 at 16:17
  • Agreed that it is nice that they handle that for you rather than making a list and passing that, but being able to use the __ notation to traverse the database is much easier and consistent. – leech Mar 26 '12 at 13:19