[Fixed]-How to build a Slack-like left panel in Django to minimize database access

1đź‘Ť

âś…

If you’re talking about a single HTML page and don’t want to re-engineer the site to use a front-end JavaScript framework with web service calls, caching can save many database calls. While I’d recommend memcached or something similar, database caching is the easiest to set up. Add this to settings:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'django_db_cache',
    }
}

Then run this command to create the DB cache:

django-admin createcachetable

Wrap the section of your template is something like this:

{% cache 3600 "leftnav-" request.user.get_username %}
.......
{% endcache %}

That would create a cache entry for the next hour with the key “leftnav-username” – and you’d have to delete it from the cache when the user adds or deletes and item to it.

You’ll probably also want to use a dummy cache in your development environment once you’re done. This basically turns off caching in development:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

Good luck!

Leave a comment