team-rf
team-rf

Reputation: 241

Caching or prefetching Django's inverse relationships

Consider a shema with a Publishers table and a Books table so that

def Publisher(models.Model):
  city = models.CharField()
  ...

def Book(models.Model):
  title = models.CharField()
  publisher = models.ForeignKey(Publisher)

In my template I wish to display a list of certain publishers with all its books. In my view function I fetch the desired Publishers with something like

publishers=Publisher.objects.filter(city='NY')

Then in my view I iterate over publishers and publishers.book_set.all like

{% for p in publishers %}
....
   {% for b in p.book_set.all %}

This works as expected except that it obviously hits the db like a zillion times.

How can I optimise the code so that django only hits the db once or twice?

Upvotes: 2

Views: 1334

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239430

In Django 1.4+, use prefetch_related

Publisher.objects.filter(city='NY').prefetch_related('book_set')

In Django <1.4, use django-batch-select.

Upvotes: 7

Related Questions