I've got two models that are relevant here; Item
and Category
, and they look as follows:
class Category(models.Model):
name = models.CharField(max_length=200)
items = models.ManyToManyField(Item)
class Item(models.Model):
name = models.CharField(max_length=200)
I want to create a page that lists all Categories
and their respective Items
. I realise I can just iterate over Category.objects.all()
and retrieve .items.all()
for each of those instances, but that seems terribly inefficient. Is there not a way to do this in a constant number of queries rather than one that scales with the number of categories? I envision the result to be some sort of 2D data structure of Categories
containing Items
that I can then iterate over in my template in a nested loop.
I've seen questions like this one that deal with a similar problem, but those typically revolve around some Item
instance that they wish to look up (which, indeed, can be done in a constant number of queries).