python django配置多数据库,多数据库的操作

settings

你好! 这是你第一次使用 **Markdown编辑器** 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

项目同名目录下新增

database_router.py文件
在这里插入图片描述
database_router.py文件内容如下:

from django.conf import settings

DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING


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 = {'app1': 'db1', 'app2': 'db2'}
    """

    def db_for_read(self, model, **hints):
        """"Point all read operations to the specific database."""
        if model._meta.app_label in DATABASE_MAPPING:
            return DATABASE_MAPPING[model._meta.app_label]
        return None

    def db_for_write(self, model, **hints):
        """Point all write operations to the specific database."""
        if model._meta.app_label in DATABASE_MAPPING:
            return DATABASE_MAPPING[model._meta.app_label]
        return None

    def allow_relation(self, obj1, obj2, **hints):
        """Allow any relation between apps that use the same database."""
        db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
        db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
        if db_obj1 and db_obj2:
            if db_obj1 == db_obj2:
                return True
            else:
                return False
        return None

    def allow_syncdb(self, db, model):
        """Make sure that apps only appear in the related database."""

        if db in DATABASE_MAPPING.values():
            return DATABASE_MAPPING.get(model._meta.app_label) == db
        elif model._meta.app_label in DATABASE_MAPPING:
            return False
        return None

    def allow_migrate(self, db, app_label, model=None, **hints):
        """
        Make sure the auth app only appears in the 'auth_db'
        database.
        """
        if db in DATABASE_MAPPING.values():
            return DATABASE_MAPPING.get(app_label) == db
        elif app_label in DATABASE_MAPPING:
            return False
        return None

生成sql语句

python manage.py makemigrations

执行sql语句

如果不是defalut(默认数据库)要在命令后边加 --database=数据库对应的settings.py中的名称 (可以让settings.py中的名字==数据库的名字),如: --database=db1
python manage.py migrate --database=db_name

app增删改查的用法

  • 查询
    Your_Model.objects.using(‘db_name’).all()
  • 保存
    your_obj.save(using=‘db_name’)
  • 删除
    your_obj.delete(using=‘db_name’)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Django配置多个数据库,你需要进行以下步骤: 1. 在Django项目的settings.py文件中,找到DATABASES配置项。默认情况下,该配置项包含一个名为"default"的数据库配置。 2. 添加一个新的数据库配置,可以使用任何你想要的名称,例如"second_db"。在DATABASES中添加一个新的字典,类似于以下示例: ```python DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'first_database', 'USER': 'your_username', 'PASSWORD': 'your_password', 'HOST': 'localhost', 'PORT': '3306', }, 'second_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'second_database', 'USER': 'your_username', 'PASSWORD': 'your_password', 'HOST': 'localhost', 'PORT': '3306', } } ``` 在上面的示例中,我们添加了一个名为"second_db"的数据库配置,并提供了相应的数据库连接信息。 3. 在你的Django应用程序中,如果你希望使用新的数据库配置,你可以在models.py中为特定模型指定数据库。在模型类的内部,可以使用`using`属性来指定要使用的数据库配置。例如: ```python class MyModel(models.Model): # 模型字段定义... class Meta: using = 'second_db' ``` 通过将模型的`Meta`类中的`using`属性设置为你想要使用的数据库配置名称,你可以将该模型与特定的数据库关联起来。 这样,你就可以在Django配置多个数据库,并根据需要在应用程序中使用不同的数据库配置。记得根据实际情况修改数据库引擎、数据库名、用户名、密码、主机和端口等信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值