In most of the cases you’ll have forward relations (foreign keys to something)
and can use select_related to fetch that data on the same query. However, in
some cases you cannot design your models that way and need data from reverse
relations (models that have foreign keys to your objects).

Django 1.4 has prefetch_related for this, however, this framework provides greater
flexibility than Django 1.4’s prefetch_related queryset method at the cost
of writting the mapping and query functions for the data. This has the advantage
that you can do things prefetch_related cannot (see the latest_book example
bellow).

Installation guide

Install it:

pip install django-prefetch

Use it as your model’s default manager (or as a base class if you have custom
manager).

from prefetch import P
for a in Author.objects.prefetch(P('latest_n_books', count=5)):
print a.latest_5_book

Note

P is optional and you can only use for prefetch definitions that are Prefetcher subclasses. You can’t use it with prefetcher-instance style
definitions like in the first example. Don’t worry, if you do, you will get an exception explaining what’s wrong.