单django应用程序使用多个sqlite3文件的数据库

smi*_*tel 2 python sqlite django django-models

我的django应用程序中有两个模型,我希望他们的表/数据库存储在单独的db/sqlite3文件中,而不是默认的"db.sqlite3"文件中.



例如:
我的models.py有两个类TrainBus,我希望它们存储在train.dbbus.db中

小智 8

当然,您可以随时使用Train.objects.using('train')您的调用,并选择正确的数据库(假设您定义了一个train在您的数据库中调用的数据库)settings.py.

如果您不想这样做,我遇到了类似的问题,并根据您的情况调整了我的解决方案.它部分基于这篇博客文章,数据库路由器的Django文档就在这里.

使用此解决方案,您当前的数据库不会受到影响,但您当前的数据也不会传输到新数据库.根据您的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'}
Run Code Online (Sandbox Code Playgroud)

在名为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
Run Code Online (Sandbox Code Playgroud)

(编辑:这也是Joey Wilhelm建议的)