網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
Django項(xiàng)目配置連接多個(gè)數(shù)據(jù)庫(kù)的方法記錄_python
作者:wuyepiaoxue789 ? 更新時(shí)間: 2022-07-14 編程語(yǔ)言一個(gè)APP對(duì)應(yīng)一個(gè)默認(rèn)數(shù)據(jù)庫(kù),若連接其他數(shù)據(jù)庫(kù)用".using()"
Author.objects.using('db02').all()
1、在項(xiàng)目settings中增加數(shù)據(jù)庫(kù)配置
# 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改成項(xiàng)目名,默認(rèn)default不用修改
DATABASE_ROUTERS = ['MyProject.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'app01': 'default',
'app02': 'db_2',
}
2、在項(xiàng)目根目錄下Myproject/Myproject 新建數(shù)據(jù)庫(kù)路由文件database_router.py
直接復(fù)制以下代碼,無(wú)需修改
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類對(duì)應(yīng)要鏈接的數(shù)據(jù)庫(kù)
反向生成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ù)庫(kù)
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ù)庫(kù),所以在此無(wú)需指定
db_table = 'names'
# 編輯app02下的models.py:
class Classnum(models.Model): #該model使用default數(shù)據(jù)庫(kù)
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ù)庫(kù)
# 同步default節(jié)點(diǎn)數(shù)據(jù)庫(kù),只運(yùn)行不帶 --database參數(shù)的命令,不對(duì)其他數(shù)據(jù)庫(kù)進(jìn)行同步
python manage.py makemigrations
python manage.py migrate
# 同步db02節(jié)點(diǎn)數(shù)據(jù)庫(kù):
python manage.py makemigrations
python manage.py migrate --database=db02
5、若要連接配置外的數(shù)據(jù)庫(kù)
Author.objects.using('other').all()
my_object.save(using='legacy_users')
my_object.delete(using='legacy_users')
移動(dòng)對(duì)象到另一個(gè)數(shù)據(jù)庫(kù)時(shí)會(huì)發(fā)生主鍵沖突,可以使用obj.pk方法清除主鍵再保存對(duì)象?
>>> p = Person(name='Fred')
>>> p.save(using='first')
>>> p.pk = None # Clear the primary key.
>>> p.save(using='second') # Write a
總結(jié)
原文鏈接:https://blog.csdn.net/wuyepiaoxue789/article/details/124799680
相關(guān)推薦
- 2022-07-15 VBScript編寫Windows防止鎖屏腳本程序_vbs
- 2022-05-20 ElasticSearch 7.X系列之:查詢分析索引磁盤使用空間_disk_usage
- 2023-07-02 Python配置文件管理之ini和yaml文件讀取的實(shí)現(xiàn)_python
- 2022-07-28 Redis基本數(shù)據(jù)類型Zset有序集合常用操作_Redis
- 2022-07-22 URLClassLoader加載Class時(shí)的類初始化問(wèn)題
- 2022-05-24 Python?6種基本變量操作技巧總結(jié)_python
- 2021-12-04 C#獲取Windows10屏幕縮放比例的操作方法_C#教程
- 2023-05-24 Python?的第三方調(diào)試庫(kù)????pysnooper???使用示例_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支