Django, multiple DB hits when repeating one related query

Viewed 212

This is the model:

class Category(models.Model):
    name = models.TextField()

class Post(models.Model):
    category = models.ForeignKey(Category)

Now, I want to get posts of a category:

category = Category.objects.get(id=1)

posts = category.post_set.all()
# this line hit the DB

posts = category.post_set.all()
# and this line hit the DB again!

How to use the cached result in these relations. I use Django rest-framework and it makes DB hit multiple times for each instance.

1 Answers

You can work with .prefetch_related(…) [Django-doc]:

category = Category.objects.prefetch_related('posts').get(id=1)

This will load the related objects, and will do the JOINing at the Django/Python layer. This thus means that the .all() calls will use the prefetched objects.

Related