djangodjango-queryset

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?


Solution

  • 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.