我的 Django 应用程序中有两个模型,我希望将它们的表/数据库存储在单独的 db/sqlite3 文件中,而不是默认的“db.sqlite3”文件中。
例如:
我的 models.py 有两个类 Train 和 Bus,我希望它们存储在 train.db 和 bus.db
最佳答案
当然你总是可以只使用Train.objects.using('train')
为您的电话选择正确的数据库(假设您在 train
中定义了一个名为 settings.py
的数据库。
如果您不想这样做,我遇到了类似的问题,我根据您的情况调整了解决方案。它部分基于 this blog article数据库路由器的 Django 文档是 here .
使用此解决方案,您当前的数据库不会受到影响,但您当前的数据也不会转移到新数据库。根据您的 Django 版本,您需要包含 allow_syncdb
或 allow_migrate
的正确版本.
在 settings.py 中:
DATABASES = {
'default': {
'NAME': 'db.sqlite3',
'ENGINE': 'django.db.backends.sqlite3',
},
'train': {
'NAME': 'train.db',
'ENGINE': 'django.db.backends.sqlite3',
},
'bus': {
'NAME': 'bus.db',
'ENGINE': 'django.db.backends.sqlite3',
},
}
DATABASE_ROUTERS = [ 'yourapp.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {'train': 'train', 'bus': 'bus'}
在一个名为 database_router.py 的新文件中:
from django.conf import settings
class DatabaseAppsRouter(object):
"""
A router to control all database operations on models for different
databases.
In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
will fallback to the `default` database.
Settings example:
DATABASE_APPS_MAPPING = {'model_name1': 'db1', 'model_name2': 'db2'}
"""
def db_for_read(self, model, **hints):
"""Point all read operations to the specific database."""
return settings.DATABASE_APPS_MAPPING.get(model._meta.model_name, None)
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
return settings.DATABASE_APPS_MAPPING.get(model._meta.model_name, None)
def allow_relation(self, obj1, obj2, **hints):
"""Have no opinion on whether the relation should be allowed."""
return None
def allow_syncdb(self, db, model): # if using Django version <= 1.6
"""Have no opinion on whether the model should be synchronized with the db. """
return None
def allow_migrate(db, model): # if using Django version 1.7
"""Have no opinion on whether migration operation is allowed to run. """
return None
def allow_migrate(db, app_label, model_name=None, **hints): # if using Django version 1.8
"""Have no opinion on whether migration operation is allowed to run. """
return None
(编辑:这也是 Joey Wilhelm 的建议)
关于python - 单个 django 应用程序使用多个 sqlite3 文件作为数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29840382/