欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django項目配置連接多個數(shù)據(jù)庫的方法記錄

 更新時間:2022年05月18日 14:20:44   作者:wuyepiaoxue789  
最近在進行django項目開發(fā)的時候,遇到了需要連接兩個MySQL數(shù)據(jù)庫的問題,下面這篇文章主要給大家介紹了關于Django項目配置連接多個數(shù)據(jù)庫的相關資料,需要的朋友可以參考下

一個APP對應一個默認數(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改成項目名,默認default不用修改
DATABASE_ROUTERS = ['MyProject.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    'app01': 'default',
    'app02': 'db_2',
}

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

直接復制以下代碼,無需修改

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類對應要鏈接的數(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ù)庫進行同步
 
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ù)庫的文章就介紹到這了,更多相關Django配置連接多數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • python生成密碼字典的方法

    python生成密碼字典的方法

    今天小編就為大家分享一篇python生成密碼字典的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • python畫圖時給圖中的點加標簽和plt.text的使用

    python畫圖時給圖中的點加標簽和plt.text的使用

    這篇文章主要介紹了python畫圖時給圖中的點加標簽和plt.text的使用,利用matplotlib模塊畫各城市2019-nCoV疫情確診人數(shù)和節(jié)前流入人口數(shù)的圖的時候遇到了要給圖中的點加上標簽示意,需要的朋友可以參考一下
    2022-03-03
  • WxPython中控件隱藏與顯示的小技巧

    WxPython中控件隱藏與顯示的小技巧

    這篇文章主要介紹了WxPython中控件隱藏與顯示的小技巧,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • Python實現(xiàn)滑雪小游戲

    Python實現(xiàn)滑雪小游戲

    這篇文章主要為大家詳細介紹了Python實現(xiàn)滑雪小游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • python深度優(yōu)先搜索和廣度優(yōu)先搜索

    python深度優(yōu)先搜索和廣度優(yōu)先搜索

    這篇文章主要介紹了python實現(xiàn)圖的深度優(yōu)先搜索和廣度優(yōu)先搜索相關知識點,對此有興趣的朋友學習下。
    2018-02-02
  • Python中實現(xiàn)文本預處理的方法小結

    Python中實現(xiàn)文本預處理的方法小結

    文本數(shù)據(jù)是數(shù)據(jù)科學和自然語言處理領域的關鍵組成部分,本文將深入探討Python中文本預處理的關鍵步驟,并提供豐富的示例代碼,希望對大家有所幫助
    2023-12-12
  • python 使用MyQR和qrcode來制作二維碼

    python 使用MyQR和qrcode來制作二維碼

    這篇文章主要介紹了python 如何使用MyQR和qrcode來制作二維碼,幫助大家更好的理解和學習使用python,感興趣的朋友可以了解下
    2021-05-05
  • Python使用numpy模塊創(chuàng)建數(shù)組操作示例

    Python使用numpy模塊創(chuàng)建數(shù)組操作示例

    這篇文章主要介紹了Python使用numpy模塊創(chuàng)建數(shù)組操作,結合實例形式分析了Python使用numpy模塊實現(xiàn)數(shù)組的創(chuàng)建、賦值、修改、打印等相關操作技巧與注意事項,需要的朋友可以參考下
    2018-06-06
  • python中requests和https使用簡單示例

    python中requests和https使用簡單示例

    這篇文章主要介紹了python中requests和https使用簡單示例,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • Django項目中包含多個應用時對url的配置方法

    Django項目中包含多個應用時對url的配置方法

    今天小編就為大家分享一篇Django項目中包含多個應用時對url的配置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05

最新評論