Note that if you use iterator() to run the query, prefetch_related() calls will be ignored since these two optimizations do not make sense together.
As such, it appears that restat is querying the DB (doing a full scan), just to get a count that's never used, and then the iterator is called, which explicitly discards the previous cached result. This should reduce some of the overhead when running restat as we work to optimize this loop further.
Reading the django docs,
prefetch_related
anditerator
are incompatible.https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related
As such, it appears that restat is querying the DB (doing a full scan), just to get a count that's never used, and then the iterator is called, which explicitly discards the previous cached result. This should reduce some of the overhead when running restat as we work to optimize this loop further.