Question

I have a small issue, which I know must be easy...however, I can't seem to find the best way to do this, preferably in one query in my view.

class Category(models.Model):
    ...

class SubCategory(models.Model):
    category = models.ForeignKey(Category)
    ...

I am able to get the subcategories and categories in one query like so, but it's not really what I need:

...
subcategories = SubCategory.objects.select_related('category')
subcategories = subcategories.filter(is_active=True)

What I really need is the reverse so I get all Categories and their associated Subcategories, but I have no idea how to do that as the Category object does not have a foreign key reference to Subcategory as a many to many...it's set up like that for a reason. (Note: It's set up this way since I have my Subcategories inline on the Category admin so I can add subcategories while on the Category add/edit and can drag and drop the subcategories in my preferred order).

I'd want something like this, just sudo output structure:

<Category object>
    <SubCategory object>
    <SubCategory object>
    <SubCategory object>
<Category object>
    <SubCategory object>
    <SubCategory object>
    <SubCategory object>
<Category object>
    <SubCategory object>
    <SubCategory object>
    <SubCategory object>
....

Can anyone point me in the right direction? Any help is appreciated. Thanks in advance.

Was it helpful?

Solution

Is that what you need?

category = Category.objects.get(pk=primary_key)
subcategories = category.subcategory_set.all()

OTHER TIPS

This is what I was really after. Saw your post AFTER I figured it out...but thanks so much for the help!

categories = Category.objects.prefetch_related('subcategory_set')
categories = categories.filter(is_active=True)

This gives me everything I need without querying the database another time for each category.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top