库的配置
1.读写分离
#settings.py 配置库信息,生成2个库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'db2': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db2.sqlite3'),
},
}
python3 manage.py makemigrations #生成迁移文件
python3 manage.py migrate --database db2 #db2数据库迁移
ret = model.Student.objects.all().using('db2')#查询db2库所有数据
models.Student.object.using("default").create(name='xxoo')#往default库写入信息
#db2查询name='ss',并更改name,并保存在default库中
obj = models.Stundet.objects.using('db2').get(name='ss')
obj.name = "sha"
obj.save(using="default")
#myrouter.py
class Router:
def db_for_write(self,model,**kwargs):
return "db2"
def db_for_read(self,model,**kwargs):
return "default"
#settings.py配置
DATABASE_ROUTERS=['myrouter.Router',]
2.一主多从
#myrouter.py
class Router:
def db_for_write(self,model,**kwargs):
return "default"
def db_for_read(self,model,**kwargs):
return random.choice(['db2','db3',"db4"])
#settings.py配置
DATABASE_ROUTERS=['myrouter.Router',]
3.分库分表
#settings.py配置
#myrouter.py
class Router:
"""
app01 model db1
app02 model db2
"""
def db_for_write(self,model,**kwargs):
app_name = model._meta.app_label#此操作能获得app的名字
if app_name == "app01":
return "db1"
elif app_name == "app02":
return "app02"
def db_for_read(self,model,**kwargs):
app_name = model._meta.app_label#此操作能获得app的名字
if app_name == "app01":
return "db1"
elif app_name == "app02":
return "app02"
4.Django执行原生SQL
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "temp.settings")
djnago.setup()
#以上配置django环境
#extra方法:
from app01 import models
#从Student,找id大于1的对象值
ret = models.Student.object.all().extra(where=['id>%s'],params=['1']).values()
print(ret)
#raw方法:
ret = models.Student.objects.raw('select * from main.app01_classes')
print(ret)
for i in ret:
print(i)#拿到学生对象
#connection方法:
from django.db import connections
#cursor = connections.cursor()
cursor = connections['db2'].cursor()#指向db2库
cursor.execute("""select * from main.app_classes where id=%s""",[1,])
row = cursor.fetchall()
print(row)