eva
eva

Reputation: 57

How to get all related objects of all objects in a Queryset?

Unfortunately I cant find a straight-forward answer to this even though there are several related questions.

Say we have:

class Category(models.Model):
    name = models.CharField(max_length=50)

class SubCategory(models.Model):
    name = models.CharField(max_length=50)
    category = models.ForeignKey(Category,on_delete=CASCADE, blank=True, null=True, related_name='subcategories')

I know I can get all the subcategories of a specific category by some_category.subcategories.all()

But how do I get a queryset of all subcategories of all categories in a queryset?

Upvotes: 1

Views: 1776

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477694

You can obtain all Subcategorys that are linked to a collection of Categorys with:

Subcategory.objects.filter(category__in=mycategories)

We here use the __in lookup [Django-doc] to retrieve only the Subcategorys for which the category is in mycategories.

Upvotes: 1

Related Questions