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 Subcategory
s that are linked to a collection of Category
s with:
Subcategory.objects.filter(category__in=mycategories)
We here use the __in
lookup [Django-doc] to retrieve only the Subcategory
s for which the category is in mycategories
.