Django

Python garbage collector cannot free queryset memory while references remain

warning
Resource ContentionUpdated Mar 15, 2026(via Exa)
Technologies:
How to detect:

After queryset iteration completes, memory doesn't shrink because _result_cache list holds references to all model instances. Python's reference counting GC cannot collect objects until reference count reaches zero, even after loop finishes.

Recommended action:

In long-running workers (management commands, Celery tasks), explicitly delete queryset reference with 'del qs' then call gc.collect() to ensure Python reclaims memory promptly. Without the del, gc.collect() does nothing useful.