Skip to main content
 首页 » 编程设计

python之为什么 Django 迁移在不使用时在非默认数据库上创建表

2024年10月24日38artech

比如说,我有多个应用程序,其中一个将使用它自己的数据库(使用 sqlite3 后端)。所以,我这样写设置:

DATABASES = { 
    'default': { 
        'ENGINE': 'django.db.backends.postgresql_psycopg2', 
        'NAME': 'default', 
         # and other settings 
     } 
} 
    'special': { 
        'ENGINE': 'django.db.backends.sqlite3', 
        'NAME': 'special.sqlite3', 
    } 
} 
 
DATABASE_ROUTERS = ['special.routers.SpecialRouter', ] 

现在,当我运行时:

./manage.py makemigrations special 
./manage.py migrate 

它没有对默认 数据库执行查询。这是应该的。但是,当我运行时:

./manage.py migrate --database=special 

所有那些只应存在于 postgresql 中的模型都是在我的 sqlite3 数据库中创建的。包括 auth_permissions、auth_goups 和所有其他。这是默认行为还是错误配置?

请您参考如下方法:

我试图为我的 Django 应用程序使用多个数据库,但是当我迁移数据库时,Django 将默认应用程序迁移到默认和非默认数据库。

我能够使用 router 中的 allow_migrate 方法解决此问题,如 @knbk 所述

我在 myapp/routers.py 中创建了 DBRouter,通过将 django 默认应用程序添加到 default_apps 元组来路由默认 django 应用程序以使用默认数据库

myapp/routers.py

class DBRouter(object): 
default_apps = ( 
    'admin', 
    'auth', 
    'contenttypes', 
    'sessions', 
    'messages', 
) 
 
def db_for_read(self, model, **hints): 
    if model._meta.app_label in self.default_apps: 
        return 'default' 
    return None 
 
def db_for_write(self, model, **hints): 
    if model._meta.app_label in self.default_apps: 
        return 'default' 
    return None 
 
def allow_migrate(self, db, app_label, model_name=None, **hints): 
    if app_label in self.default_apps: 
        return db == 'default' 
    return None 

使用 App router 在设置中添加该路由器

settings.py

DATABASE_ROUTERS = ['activity_manager.routers.DBRouter', 'activity_manager.routers.AppRouter']