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
settings.pyConfigure multiple database connection strings that need to be connected in
databases = { ' default ': { ' Django.db.backends.sqlite3 ', ' NAME ': os.path.< Span class= "Hljs-keyword" >join (Base_dir, ' Sqlite3 '),}, ' db01 ' : { ' Django.db.backends.sqlite3 ', ' NAME ': Os.path. join (Base_dir, ' db_01 '),}, ' db02 ' : { ' Django.db.backends.sqlite3 ', ' NAME ': Os.path. join (Base_dir, ' db_02 '),},}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
Suppose we now use 3 databases, a default library, a db01 and a db02
2. Setting the routing rules method for a database
In the settings.py configureDATABASE_ROUTERS
DATABASE_ROUTERS = [‘Prject.database_router.DatabaseAppsRouter‘]
Project: Established Django Project name (PROJECT_NAME)
Database_router: Defines the routing rule database_router.py file name, which can be defined by itself
Databaseappsrouter: The class name of the routing rule, which is database_router.py defined in the 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 a file under the project Engineering root path (with the settings.py file level) database_router.py :
From django.confImport settingsdatabase_mapping = settings. Database_apps_mappingClassDatabaseappsrouter(object):"" A router to control all database operations on models for different 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 '} ' ""DefDb_for_read(self, model, **hints):"," "point all read operations to the specific database." "" "If Model._meta.app_labelIn database_mapping:return Database_mapping[model._meta.app_label]ReturnNoneDefDb_for_write(self, model, **hints):"" "Point all write operations to the specific database." "" "If Model._meta.app_labelIn database_mapping:return Database_mapping[model._meta.app_label]ReturnNoneDefAllow_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_obj1and Db_obj2:if db_obj1 = = Db_obj2:ReturnTrueElseReturnFalseReturnNoneDefAllow_syncdb(self, DB, model):"" "Make sure this apps only appear in the related database." "If DBIn Database_mapping.values ():Return Database_mapping.get (model._meta.app_label) = = dbElif Model._meta.app_labelin database_mapping: return False return none def allow_migrate (self, DB, App_label, Model=None , **hints): if db in database_mapping.values (): return Database_mapping.get (App_label) = = db elif app_label in Database_mapping: return false return none
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21st
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
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 you do not specify it, it is created to the name of the default database configured in.
As follows:
app01under Create models
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"
app02under Create models
ClassUsers(Models. Model): Username = models. Charfield (max_length=Password = models. Charfield (max_length=Age = Models. Integerfield ()Def__str__(self):Return "app02%s"% self.username class Span class= "hljs-title" >meta:app_label = "APP02" class book "Users", On_delete=models. CASCADE) BookName = models. Charfield (Max_length=100) def Span class= "Hljs-title" >__str__return "%s:%s "% (Self.user.username, self.bookname) Class meta:app_label = "app02"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
app03App_label is not specified in Create models, 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 ()
Such a way to operate
Django Multi-database configuration