Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure a Django project to connect to multiple databases

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you how to configure the Django project to connect to multiple databases. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article.

An APP corresponds to a default database. If you connect to other databases, use ".using ()"

Author.objects.using ('db02') .all ()

1. Add database configuration to the project settings

# settings.py DATABASES = {'default': {' ENGINE': 'django.db.backends.oracle',' NAME': 'orcl19c',' USER': "username01", 'PASSWORD': "password01",' HOST': "110.10.1.11", 'PORT': 1511,},' db_2': {'ENGINE':' django.db.backends.oracle' " Change MyProject below 'NAME':' orcl19c', 'USER': "username02",' PASSWORD': "password02", 'HOST': "120.20.2.22",' PORT': 1512,}} # to project name The default default does not need to modify DATABASE_ROUTERS = ['MyProject.database_router.DatabaseAppsRouter'] DATABASE_APPS_MAPPING = {' app01': 'default',' app02': 'db_2',}

2. Create a new database routing file database_router.py in Myproject/Myproject under the root directory of the project

Copy the following code directly without modification

From django.conf import settings DATABASE_MAPPING = settings.DATABASE_APPS_MAPPINGclass 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_ map [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_ map [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

3. After using inspectdb to generate the model class of each app in reverse, configure the model class to correspond to the database to be linked

Generate the models.py command in reverse:

Python manage.py inspectdb-- database db1 TableName1 > app01/models.py python manage.py inspectdb-- database db2 TableName2 > app02/models.py# Edit models.py:class Names (models.Model) under app01: # the model uses the default database id=models.CharField (primary_key=True,max_length=100, blank=True, null=True) name=models.CharField (max_length=32,primary_key=True,unique=True) class Meta: # app_label = 'app01' # because the model connects to the default database So there is no need to specify db_table = 'names' # to edit models.py:class Classnum (models.Model) under app02: # the model uses the default database id=models.CharField (primary_key=True,max_length=100, blank=True, null=True) classnum=models.CharField (max_length=32,primary_key=True,unique=True) class Meta: app_label =' app02' db_table = 'classnum'

4. Synchronize the database

# synchronize default node database, only run commands without-- database parameter, and do not synchronize other databases. # synchronize db02 node database: python manage.py makemigrations python manage.py migrate-- database=db02

5. To connect to a database outside the configuration

Author.objects.using ('other'). All () my_object.save (using='legacy_users') my_object.delete (using='legacy_users')

A primary key conflict occurs when moving an object to another database. You can use the obj.pk method to clear the primary key and then save the object.

> p = Person (name='Fred') > p.save (using='first') > p.pk = None # Clear the primary key. > > p.save (using='second') # Write an is all the content of this article "how to configure a Django project to connect to multiple databases". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report