0

I've got a heirarchy like so:

Parent Cat
     Sub Cat
         Item
     Sub Cat
         Item
         Item
Parent Cat
...

Having the name/instance of a parent category I'd like to get all items which are related to the parent cat. I'm currently using Django-Categories which makes use of Django-MTPP but I can't figure out how to do this without building the for loops myself. Thought the whole point of these packages were so I wouldn't have to do that.

My models look like:

class Item(models.Model):
    title = models.TextField() # `null` and `blank` are false by default
    category = models.ForeignKey('ProductCategory')
    price = ....

    def __unicode__(self):  # Python 3: def __str__(self):
        return self.title

from categories.models import CategoryBase

class ProductCategory(CategoryBase):

    class Meta:
        verbose_name_plural = 'simple categories'

I've tried doing:

parent_category = ProductCategory.objects.get(slug=parent_cat, parent=None)
items = parent_category.item_set.all()

But that doesn't produce any results.

KingFu
  • 1,358
  • 5
  • 22
  • 42

1 Answers1

3

You should filter your items:

items = Item.objects.filter(category__parent=parent_category)

The double score is used to follow model relationships or to use more complex lookups than a simple equal. Documentation here

Germano
  • 2,452
  • 18
  • 25
  • This was the first thing I tried, and doesn't produce any results. I assume because category is set to the sub category and not the parent category – KingFu Aug 30 '13 at 14:57
  • @KingFu From your code, I'd say the opposite: your category is set to the parent :) I don't have experience with Django-Categories but you can try `items = Item.objects.filter(category__parent=parent_category)`. If it works, I'll update the answer – Germano Aug 30 '13 at 15:00
  • ah perfect that works! Although I'm not sure how the double underscore works, is `category__parent = parent_category` basically saying `if the categories parent == parent_category`? Could you update your answer and i'll accept it, thanks – KingFu Aug 30 '13 at 15:06