How to configure multiple databases for a single Django app

In Django, it is possible to configure multiple databases for a single app. Here are the steps to configure multiple databases for a single app.

  1. Define multiple database connection information in settings.py.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    },
    'db1': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database1',
        'USER': 'username1',
        'PASSWORD': 'password1',
        'HOST': 'localhost',
        'PORT': '3306',
    },
    'db2': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'database2',
        'USER': 'username2',
        'PASSWORD': 'password2',
        'HOST': 'localhost',
        'PORT': '3306',
    },
}
  1. Specify which database to use in the models.py of the app.
class Model1(models.Model):
    field1 = models.CharField(max_length=100)

    class Meta:
        app_label = 'myapp'
        db_table = 'model1'
        using = 'db1'

class Model2(models.Model):
    field2 = models.CharField(max_length=100)

    class Meta:
        app_label = 'myapp'
        db_table = 'model2'
        using = 'db2'

In the example above, Model1 and Model2 specify the use of the db1 and db2 databases, respectively.

  1. If you need to perform database operations in your view functions or elsewhere, you can use the “using” method to specify which database to use.
from myapp.models import Model1, Model2

def my_view(request):
    # 使用db1数据库
    model1_objects = Model1.objects.using('db1').all()

    # 使用db2数据库
    model2_objects = Model2.objects.using('db2').all()

By following the steps above, you can configure multiple databases for a single app and specify which database to use for database operations in models, views, and other places.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds