This article mainly introduces the Django multi-database configuration tutorial, has a certain reference value, now share to everyone, the need for friends can refer to
In a Django project, there are multiple app applications in a project that are common. Sometimes you want different apps to connect to different databases, and that's when you need to set up multiple database connections.
1. Modify the settings configuration of the project
Configuring multiple database connection strings 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_ "), },}
Suppose we now use 3 databases, a default library, a db01 and a db02
2. Setting the routing rules method for a database
Configuring Database_routers in settings.py
Database_routers = [' Prject.database_router. Databaseappsrouter ']
Project: Established Django Project name (PROJECT_NAME)
Database_router: Define the routing rule database_router.py file name, this file name can be defined by itself
Databaseappsrouter: The class name of the routing rule, which is defined in the database_router.py file
3. Set the database routing table for the app
Each app to connect to which database, you need to do the matching settings, in the settings.py file to do the following configuration:
database_apps_mapping = { # example: # ' app_name ': ' database_name ', ' app02 ': ' db02 ', ' app01 ': ' Db01 ', ' admin ': ' db01 ', ' auth ': ' db01 ', ' contenttypes ': ' db01 ', ' sessions ': ' Db01 ',}
Above the APP01, APP02 is the app name in the project, which is assigned to DB01, DB02 database respectively.
To enable Django's own tables to be created in your own defined database, you can specify: admin, Auth, contenttypes, sessions to the set database, and automatically create the default database if not specified
4. Create a database routing rule
Create the database_router.py file under the project Engineering root path (at the level of the settings.py file):
From django.conf Import settingsdatabase_mapping = settings. Database_apps_mappingclass Databaseappsrouter (object): "" "A router to control all database operations on models for DIF ferent databases. In the case a app is not a set in settings. Database_apps_mapping, the router would 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_f Or_write (self, model, **hints): "", "", "" "" "" " If Model._meta.app_label in Database_mapping:return Database_mapping[model._meta.app_label] return None def allo W_relation (self, obj1, Obj2, **hints): "" "Allow any relation between apps, 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 is 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 create a sample
When you create a models for a datasheet in your own APP, you must specify the App_label name of the table and, if not specified, create the name of the database configured in default.
As follows:
Create a 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 a 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"
App_label created models not specified in APP03, created under Default
Class Users (models. Model): username = models. Charfield (max_length=100)
6. Generating a data table
When you create a build table using Django migrate, you need to add the –database parameter, and if not, create a table in the models of the app that does not specify app_label to the database specified by default, such as:
Create a table in APP01 under Models to DB01 database "db_01"
./manage.py Migrate--DATABASE=DB01
Create a table in APP02 under Models to DB02 database "db_02"
./manage.py Migrate--DATABASE=DB02
Create a table in APP03 under models to the database "Sqlite3" of Default
./manage.py Migrate
After the creation of the above, all other operations such as create, query, delete, and so on as normal operation, no need to use a similar
Models. User.objects.using (dbname). All ()
To operate in such a way.