Search code examples
django-orm

How to clear Django's cached query after prefetch_related


I'm rendering a list of items with their related reviews. I used prefetch_related so it won't issue a new query for each item's reviews.

items = Item.objects.all().prefetch_related('reviews')

Later, I add a review and try to re-calculate the average:

item = items[0]
Review.objects.create(item=item, score=5)

# recalculate average
reviews = item.reviews.all()
...

Oh no! This list of reviews doesn't include the one I just created. How can I clear this cache so the query can be performed fresh? Or should I be creating the review differently?


Solution

  • prefetch_related(None)

    Source: https://docs.djangoproject.com/en/2.0/ref/models/querysets/