Home > Enterprise >  How to get all related objects of all objects in a Queryset?
How to get all related objects of all objects in a Queryset?

Time:10-19

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

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?

CodePudding user response:

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.

  • Related