溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Django項目怎么配置連接多個數(shù)據(jù)庫

發(fā)布時間:2022-05-18 15:48:19 來源:億速云 閱讀:108 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下Django項目怎么配置連接多個數(shù)據(jù)庫的相關(guān)知識點,內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

一個APP對應(yīng)一個默認(rèn)數(shù)據(jù)庫,若連接其他數(shù)據(jù)庫用".using()"

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

1、在項目settings中增加數(shù)據(jù)庫配置

# 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',
     'NAME': 'orcl19c', 
     'USER': "username02",
     'PASSWORD': "password02",
     'HOST': "120.20.2.22",
     'PORT': 1512,
 }
}
# 以下MyProject改成項目名,默認(rèn)default不用修改
DATABASE_ROUTERS = ['MyProject.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    'app01': 'default',
    'app02': 'db_2',
}

2、在項目根目錄下Myproject/Myproject 新建數(shù)據(jù)庫路由文件database_router.py

直接復(fù)制以下代碼,無需修改

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

3、使用inspectdb反向生成各app的model類之后,配置model類對應(yīng)要鏈接的數(shù)據(jù)庫

反向生成models.py 命令:

python manage.py inspectdb --database db1 TableName1 > app01/models.py
 
python manage.py inspectdb --database db2 TableName2 > app02/models.py
# 編輯app01下的models.py:
class Names(models.Model): #該model使用default數(shù)據(jù)庫
    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' #由于該model連接default數(shù)據(jù)庫,所以在此無需指定
        db_table = 'names'
        
# 編輯app02下的models.py:
class Classnum(models.Model): #該model使用default數(shù)據(jù)庫
    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、同步數(shù)據(jù)庫

# 同步default節(jié)點數(shù)據(jù)庫,只運行不帶 --database參數(shù)的命令,不對其他數(shù)據(jù)庫進(jìn)行同步
 
python manage.py makemigrations
 
python manage.py migrate
 
# 同步db02節(jié)點數(shù)據(jù)庫:
 
python manage.py makemigrations
 
python manage.py migrate --database=db02

5、若要連接配置外的數(shù)據(jù)庫

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

移動對象到另一個數(shù)據(jù)庫時會發(fā)生主鍵沖突,可以使用obj.pk方法清除主鍵再保存對象 

>>> p = Person(name='Fred')
>>> p.save(using='first')
>>> p.pk = None # Clear the primary key.
>>> p.save(using='second') # Write a

以上就是“Django項目怎么配置連接多個數(shù)據(jù)庫”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學(xué)習(xí)更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI