Django’s cache can make pages, database results, and other data faster to retrieve. When cached content becomes outdated—or you need to troubleshoot a caching problem—you may want to clear it. The right method depends on which cache backend and cache alias your project uses. In most cases, Django’s cache API is the safest way to remove cached data.
The quickest option is to call clear() on the cache you want to empty. You can do this from Django’s shell, from application code, or through a carefully designed administrative action. Before clearing a cache in production, check whether the cache is shared with other parts of your application: clearing it may cause a temporary increase in database queries or page-generation time.
The Quickest Way to Clear Django’s Default Cache
To clear the default cache, open the Django shell from your project directory:
python manage.py shell
Then run:
from django.core.cache import cache
cache.clear()
The cache object is Django’s shortcut for the cache configured as default in your project’s CACHES setting. Calling clear() removes all entries from that cache. You can also run the same operation in one command:
python manage.py shell -c "from django.core.cache import cache; cache.clear()"
This is usually the simplest approach when your project uses one cache and you intentionally want to empty it. It clears cached values, not your database records, uploaded files, browser data, or static files.
Clear a Specific Cache Alias
A project can define multiple cache aliases—for example, one cache for pages and another for API responses. In that case, clearing the default cache may not clear the cache you are trying to refresh. Django lets you select an alias with caches:
from django.core.cache import caches
caches["api"].clear()
Replace "api" with the alias used in your settings. A simplified configuration might look like this:
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
},
"api": {
"BACKEND": "django.core.cache.backends.redis.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/2",
},
}
To see which aliases are available, inspect CACHES in your Django settings. If your application code uses caches["api"], clear that alias rather than assuming cache.clear() will affect it. Each alias can point to a different backend and may store unrelated data.
Clear One Key Instead of the Entire Cache
Clearing everything is convenient, but it may remove useful entries that do not need refreshing. If you know the key for an outdated value, remove only that entry with delete():
from django.core.cache import cache
cache.delete("product:42")
To remove several known keys at once, use delete_many():
cache.delete_many([
"product:42",
"product:57",
"category:shoes",
])
Use the same key that was passed to cache.set() or another cache-writing method. A key that looks right may not match the stored entry if your project applies a key prefix, a version number, or a custom key function. Django automatically incorporates configured prefixes and versions when it builds the backend key, so application code should normally pass the original logical key to the cache API rather than trying to construct the backend’s internal key.
For example, this is a targeted invalidation pattern:
cache.set("product:42", product_data, timeout=300)
# After product 42 changes:
cache.delete("product:42")
If you use a predictable key scheme, targeted deletion can be easier to maintain and less disruptive than clearing the whole cache.
Clear a Cache from Django Application Code
You can call clear() from application code, such as a management command or a controlled maintenance task. A custom management command is often preferable to adding a public web endpoint, because it can be run by an authorized operator without exposing a destructive action to ordinary users.
For example, create a management command that targets a specific alias:
from django.core.cache import caches
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "Clear the API cache"
def handle(self, *args, **options):
caches["api"].clear()
self.stdout.write(self.style.SUCCESS("API cache cleared."))
Save the command in an installed application under a management/commands/ directory, then run it with python manage.py clear_api_cache, using the filename you chose. Restrict access to the server or deployment process that needs it. Avoid creating an unauthenticated URL that clears the cache; an exposed endpoint could let anyone repeatedly invalidate cached data and increase load on your application.
How the Cache Backend Affects Clearing
The cache backend determines where values are stored and how clearing behaves. Django provides several built-in backends, and projects may also use third-party backends. In general, use Django’s cache API rather than deleting files or modifying backend storage manually.
- Local-memory cache: Values are held in process memory. This backend is useful for development and some single-process deployments, but it is not shared between separate processes. Clearing it in a new management-shell process may not clear the memory of web workers that are already running. Each process has its own local cache.
-
Redis or Memcached: These backends can be shared by multiple application processes. Calling
clear()through Django clears the cache represented by the selected alias, subject to the backend’s configuration and behavior. Check whether other applications share the same Redis database or cache service before emptying it. - File-based cache: Django stores entries on disk, but the cache API should manage their removal. Avoid deleting files by hand while the application is using the cache, unless you understand the backend’s storage layout and have a specific operational reason.
-
Database cache: Django stores entries in a database table created for caching. Use
clear()or targeted deletion rather than manually emptying the table, which may bypass application expectations or affect the wrong cache.
If you use LocMemCache and a shell command appears to succeed but your running site still shows old data, process isolation may be the reason. For shared caching across multiple workers, use a shared backend such as Redis or Memcached and make sure all workers use the same alias and configuration.
Clear Cached Template Fragments
Django’s template fragment caching can store a specific part of a page under a generated key. If you know the fragment name and the values used in its vary_on list, you can generate the corresponding key with make_template_fragment_key() and delete it:
from django.core.cache import cache
from django.core.cache.utils import make_template_fragment_key
key = make_template_fragment_key(
"sidebar",
["username"],
)
cache.delete(key)
The fragment name and variation values must match the template’s {% cache %} tag. For example, if the template varies the fragment by a user’s username, pass that username when generating the key. If you do not know the exact key inputs—or need to invalidate many fragment variations—clearing the relevant cache alias or using a versioning strategy may be more practical.
What About Per-View and Page Caches?
Django’s per-view cache and cache middleware store responses using keys derived from request details, such as the URL and relevant headers. These keys are not always convenient to identify manually. If you need to refresh one page, consider whether your application can invalidate the data used to build it, or whether a short cache timeout is appropriate. If you need to remove many generated response entries at once, clearing the cache alias that stores them is straightforward, but it also removes other entries in that alias.
For recurring updates, versioned keys can make invalidation easier. Django’s cache API accepts a version argument for operations such as get(), set(), and delete(). Moving your application to a new version of a key can make old values unreachable without deleting every stored entry immediately. This approach needs consistent version handling in the code that reads and writes the values.
What Clearing Django’s Cache Does Not Clear
A call to cache.clear() affects only the selected Django cache backend and alias. It does not necessarily clear a browser’s local cache, a content delivery network (CDN), a reverse proxy, or a separate caching layer managed by your hosting provider. If a visitor still sees old content after clearing Django’s cache, check those layers as well.
Likewise, clearing the cache does not change the underlying data. If stale content is being regenerated, check whether your database, application logic, or another upstream service still contains the old value. Cache invalidation works best when the application updates or removes the relevant cached entries whenever the underlying data changes.
Common Problems When Clearing Django Cache
- The wrong cache was cleared: Confirm which alias the code uses and clear that alias explicitly.
- Old values return immediately: A request or background job may be repopulating the cache. Check the code that writes the value and the data source it reads.
- A shell command has no effect: With LocMemCache, the shell and web workers may be separate processes. With shared backends, check that they use the same server, database, alias, and settings.
- Only some pages look stale: The content may come from a different cache alias, a template fragment, a CDN, or a proxy rather than the cache you cleared.
- Clearing causes a slowdown: A full clear can force many requests to rebuild expensive results at once. Prefer targeted deletion or planned invalidation when possible.
In production, avoid using a broad Redis command such as FLUSHALL as a shortcut. It can remove data belonging to other applications or services. Prefer Django’s configured cache API, verify the target alias, and follow your team’s deployment and operational procedures.
Conclusion
To clear Django’s default cache, run from django.core.cache import cache followed by cache.clear(). To clear another configured cache, select it with caches["alias"]. For a smaller change, use delete(), delete_many(), or the template-fragment key utility instead of removing every cached entry.
The backend matters: in particular, LocMemCache is process-local, while shared backends can serve multiple workers. Check your cache alias, backend, and any CDN or proxy layers when old content persists. A deliberate invalidation strategy helps keep content fresh without creating avoidable load or removing unrelated cached data.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.