python - 单个 django 应用程序使用多个 sqlite3 文件作为数据库

标签 python django django-models sqlite

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



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

最佳答案

当然你总是可以只使用Train.objects.using('train')为您的电话选择正确的数据库(假设您在 train 中定义了一个名为 settings.py 的数据库。

如果您不想这样做,我遇到了类似的问题,我根据您的情况调整了解决方案。它部分基于 this blog article数据库路由器的 Django 文档是 here .

使用此解决方案,您当前的数据库不会受到影响,但您当前的数据也不会转移到新数据库。根据您的 Django 版本,您需要包含 allow_syncdballow_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/

相关文章:

python - Django 建立关系模型

内存使用

python - 使用正则表达式检查特定单词是否出现在其他单词之前

django - 具有FileField的Django模型-动态“upload_to”参数

python - (Django) DetailView 模板不显示信息

django - Django 模型中的 ChoiceField

python - PyCharm 摆脱 doctest 背景颜色

python - 通过Python访问Google Shopping API

在 Django 中设置分页时出现 Python 类型错误

python - 个人用户的 Django 图像未显示