Home > Article > Backend Development > Django multi-database configuration tutorial
This article mainly introduces the django multi-database configuration tutorial, which has a certain reference value. Now I share it with everyone. Friends in need can refer to it
In the django project, there are multiple databases in one project. It is very common to use multiple APPs. Sometimes you want different APPs to connect to different databases. In this case, you need to establish multiple database connections.
1. Modify the project settings configuration
Configure multiple database connection strings that need to be connected in settings.py
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'sqlite3'), }, 'db01': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_01'), }, 'db02': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db_02'), }, }
Assume we are using 3 databases now, a default library, a db01 and a db02
2. Set the routing of the database Rule method
Configure DATABASE_ROUTERS in settings.py
DATABASE_ROUTERS = ['Prject.database_router.DatabaseAppsRouter']
Project: Created django project name (project_name)
database_router: Define the name of the routing rule database_router.py file, this file name can be defined by yourself
DatabaseAppsRouter: The class name of the routing rule, this class is defined in the database_router.py file
3. Set the database routing table corresponding to the APP
Which database each APP needs to connect to needs to be matched in the settings.py file Make the following configuration:
DATABASE_APPS_MAPPING = { # example: # 'app_name':'database_name', 'app02': 'db02', 'app01': 'db01', 'admin': 'db01', 'auth': 'db01', 'contenttypes': 'db01', 'sessions': 'db01', }
The above app01 and app02 are the APP names in the project, which are assigned to the databases of db01 and db02 respectively.
In order to create django's own tables into your own defined database, you can specify: admin, auth, contenttypes, sessions to the set database. If not specified, it will be automatically created to the default ( default) in the database
4. Create database routing rules
in the root path of the project (at the same level as the settings.py file) Create database_router.py 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
5. Models creation example
In When creating models of data tables in respective APPs, you must specify the app_label name of the table. If not specified, it will be created under the database name configured in default.
is as follows:
Create models under app01
class Users(models.Model): name = models.CharField(max_length=50) passwd = models.CharField(max_length=100) def __str__(self): return "app01 %s " % self.name class Meta: app_label = "app01"
Create models under app02
class Users(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=50) age = models.IntegerField() def __str__(self): return "app02 %s" % self.username class Meta: app_label = "app02" class Book(models.Model): user = models.ForeignKey("Users", on_delete=models.CASCADE) bookname = models.CharField(max_length=100) def __str__(self): return "%s: %s" % (self.user.username, self.bookname) class Meta: app_label = "app02"
Create models in app03 without specifying app_label and create them under default
class Users(models.Model): username = models.CharField(max_length=100)
6. Generate data table
When using django's migrate to create a generated table, you need to add the --database parameter. If not, the table in the models of the APP that does not specify app_label will be created into the database specified by default, such as:
Create the table in models under app01 into the database "db_01" of db01
./ manage.py migrate --database=db01
Create the table in models under app02 into db02 In the database "db_02"
./ manage.py migrate --database=db02
Create the table in models under app03 to the default database "sqlite3"
./ manage.py migrate
After the above creation is completed, all other creation, query, deletion and other operations can be performed as usual. There is no need to use something like
models.User.objects.using(dbname).all()
Operation in this way.
Related recommendations:
How to configure the URL when the Django project contains multiple applications
The above is the detailed content of Django multi-database configuration tutorial. For more information, please follow other related articles on the PHP Chinese website!