You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django缓存路由配置:如何为指定数据库正确执行createcachetable命令

解决方案

1. CacheRouter类存放位置

你可以将该类放在项目可导入的任意模块中,最规范的放置路径是项目根目录下与settings.py同目录的routers.py文件,如果该文件不存在直接新建即可。
举个例子,如果你的项目主目录名为my_django_project,路径结构如下:

my_django_project/
├── __init__.py
├── asgi.py
├── settings.py
├── routers.py  # 新建此文件,将CacheRouter类粘贴到这里
├── urls.py
└── wsgi.py

2. 注册数据库路由到settings.py

在settings.py中添加如下配置,让Django识别你写的路由规则:

DATABASE_ROUTERS = ['my_django_project.routers.CacheRouter']

注意将上面的my_django_project替换为你实际的项目主目录名称。

3. 补充优化配置(必做,否则路由规则不生效)

你当前的配置有两处逻辑疏漏,需要修正才能达到预期效果:

  • 修正CacheRouter类的判断逻辑:缓存表对应的app_label是django_cache,原路由中route_app_labels = {'db_my_project'}的判断无法命中缓存操作,优化后的类代码如下:
class CacheRouter:
    """A router to control all database cache operations"""
    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'django_cache':
            return 'db_my_project'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'django_cache':
            return 'db_my_project'
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label == 'django_cache':
            return db == 'db_my_project'
        return None
  • 在缓存配置中指定目标数据库,在settings.py的CACHES配置项里添加DATABASE参数:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'dataframe_cache',
        'DATABASE': 'db_my_project', # 新增这一行,指定缓存用的数据库
    }
}

4. 执行生成命令

配置完成后重新执行python manage.py createcachetable,即可在db_my_project对应的MySQL数据库中生成dataframe_cache表。

内容的提问来源于stack exchange,提问作者user3288051

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:15:02