2

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I using category = Category.objects.prefetch_related("post_set") in drf view get_queryset function and its worked!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.