Home >Backend Development >Python Tutorial >How to operate multiple databases with Django in python (code)

How to operate multiple databases with Django in python (code)

不言
不言Original
2018-09-17 16:45:441440browse

The content of this article is about the method (code) of django operating multiple databases in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Add the database routing distribution file

Create the ‘database_router’ file in the project folder. Copy the following code into this file.

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

2. Configure multiple databases in the settings.py file

# Database

# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {

    'default': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'django_test',

        'HOST': '127.0.0.1',

        'USER': 'root',

        'PASSWORD': '123456',

        'PORT': '3306',

},

#配置第二个数据库

    'test': {

        'ENGINE': 'django.db.backends.mysql',

        'NAME': 'xsanjiaocheng',

        'HOST': '127.0.0.1',

        'USER': 'root',

        'PASSWORD': '123456',

        'PORT': '3306',

    }

}

#Set the database routing and change django_test to the name of your project .

DATABASE_ROUTERS = ['django_test.database_router.DatabaseAppsRouter']

#Configure the corresponding relationship between the database and the app

DATABASE_APPS_MAPPING = {
    # example:
    # 'app_name':'database_name',
    # 'app01': 'test',
    'app01': 'default',
    'app02': 'test',
}

3. Just create the data table normally in the models.py file in the corresponding app (try not to use the same table name when creating the table)

models.py in app01:

class django_test_1(models.Model):

    abc = models.CharField(max_length=20)

    class Meta:

        app_label='app01'

app02中的models.py:

class test_1(models.Model):

    tests= models.CharField(max_length=20)

4. Generate migration files

Same as before: python manage.py makemigrations

5. Migrate database

You need to specify the database name when migrating

python manage.py migrate  database=test

If you create the corresponding models.py file for the already created database, you do not need to generate a migration file. Just execute the command "python manage.py inspectdb > app02/models.py --database=test" directly.

6. Operation database

1) Manually select the database

django_test_1.objects.using('default').create(abc='hdajh')

2) Automatically select the database

No using() is added as before.

7. Configure urls.py

Import the views.py file corresponding to the app. It's better to give it an alias, or rename the views.py file.

Other usage is the same as before.

The above is the detailed content of How to operate multiple databases with Django in python (code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn