我的django应用程序中有两个模型,我希望他们的表/数据库存储在单独的db / sqlite3文件中,而不是默认的“db.sqlite3”文件中。
<小时/>
答案 0 :(得分:8)
当然,您可以随时使用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所建议的)