redis做django的缓存
``` pip install django-redis ``` ```python CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379/1", "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient", } } } ```
将session保存在redis中
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
ORM性能
-
能使用values(),就不要用对象.属性
-
select_related 主动连表 外键或者一对一
-
prefetch_related 子查询 外键或者一对一或者多对多
-
only 只查询所需要的字段 defer 排除字段
多个数据库
配置多个数据库
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'), }, }
迁移 migrate --databse db2
读写分离
手动读写分离:
写入数据库 use using
models.Student.objects.using('db2').create(name='xxxx')
读取数据库
ret = models.Student.objects.using('default').all()
读取数据库
ret = models.Student.objects.using('default').all()
for i in ret:
i.name = 'alex1111'
i.save(using='default')
通过配置,自动读写分离
app01.router:创建py文件,写类,定义方法
class Router:
def db_for_read(self, model, **kwargs):
return 'default'
def db_for_write(self, model, **kwargs):
return 'db2'
settings.py中
DATABASE_ROUTERS = ['app01.router.Router']
一主多从
写入一个数据中,从多个数据库读取
一主多从
import random
class Router:
def db_for_read(self, model, **kwargs):
return random.choice(['db1', 'db2', 'db3'])
def db_for_write(self, model, **kwargs):
return 'default'
分库分表
app01的表放在db1
app02的表放在db2
分库分表
class Router:
def db_for_read(self, model, **kwargs):
label = model._meta.app_label
if label == 'app01':
return 'db1'
elif label == 'app02':
return 'db2'
def db_for_write(self, model, **kwargs):
label = model._meta.app_label
if label == 'app01':
return 'db1'
elif label == 'app02':
return 'db2'
model
model._meta.app_label app名称
model._meta.model_name model名称