1

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

Community
  • 1
  • 1
Joost
  • 4,094
  • 3
  • 27
  • 58

1 Answers1

1

This is exactly what prefetch_related does.

In fact, that gives you a queryset, but with the .items.all() pre-populated.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Exactly what I was looking for. The example is nearly identical to my situation. Thanks! – Joost Apr 13 '15 at 09:39