一般获取查询都会模型.objects.all()但是数据太大就会冗余。所以要优化查询。(直接从redis去获取数据而不是所有的数据库,还要写crontab定时任务定时更新redis的数据)
在settings.py设置以下代码
# 缓存配置
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
# 修改默认存储的类型,默认为bytes
"CONNECTION_POOL_KWARGS":{'decode_responses':True}
}
}
}
goods/views.py(优化代码)
import json
@api_view(['GET'])
def home(request):
# TODO: 如何优化查询, 如何设置存储的格式(默认为bytes), json
# 如果使用redis缓存数据,类型: hash散列
# hset key field value
# hset goods main_wheels MainWheelSerializer(main_wheels, many=True).data
# hset goods main_navs MainNavSerializer(main_navs, many=True).data
conn = get_redis_connection()
redis_main_wheels = conn.hget('goods', 'main_wheels')
if not redis_main_wheels:
main_wheels = MainWheel.objects.all()
new_main_wheels = MainWheelsSerializer(main_wheels, many=True).data
# 存储结果为json格式数据,json.dumps()
value_wheels = json.dumps(new_main_wheels)
conn.hset('goods', 'main_wheels', value_wheels)
# 存储为字符串类型的结果值,需转换为字典,json.loads()
old_main_wheels = json.loads(redis_main_wheels)
网友评论