1.自连接
(1)自连接的定义
通过外键关联自己完成自连接数据模型的定义.,关联自己的外键,关联类型 ‘self’,而不是类型
classs GoodType(models.Model):
id = models.AutoField(primary_key=True, verbose_name='商品类型编号')
name = models.CharField(max_length=50, verbose_name='商品类型名称')
cover = models.ImageField(upload_to='static/images/goodType', default='static/images/default.jpg')
intro = models.TextField(verbose_name='商品类型描述')
parent = models.ForeignKey('self', null=True, blank=True)
(2)自连接中的查询问题
自连接查询: 1->n gt.goodstype_set.all()
n->1 gt.parent # parent为类型中定义的变量
一级类型->所有商品:
类型关联查询:gt_one.goodstype_set.all()
遍历:gt_two.goods_set.all()
通过数据库查询:
gt_one = goodstype.objects.filter(pk=gt_id)
gt_two = goodstype.objects.filter(parent=gt_one)
goods = goods.objects.filter(goodstype_two)
二级类型->所有商品
类型关系查询:gt_two.goods_set.all()
通过数据库查询:
gt_two.goods.objects.filter(pk=gt_id)
good_list = goods.objects.filter(goodstype=f=gt_two)
通过类型关系查询,可以直接在网页中操作
通过数据库查询,必须通过视图处理函数,在函数中执行查询操作
2.缓存
(1)准备工作
1)安装redis数据库
2)安装django-redis插件
pip install django-redis
3)了解官方网站
(2)操作过程
1)安装配置支持缓存操作
修改配置文件setting.py,添加如下代码
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://127.0.0.1:6379/1",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
}
}
}
2)向缓存中添加数据
from django.core.cache import cache
cache.set("foo", "value", timeout=25) # 如果未设置timeout,默认永久
3)从缓存中读取数据
from django.core.cache import cache
value = cache.set("foo", "value", timeout=25)
4)更新缓存中的数据
5)将session数据也存储在缓存中
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "default"
(3)案例
def index(request):
print('开始从缓存中查询所有商品类型')
gt_list = cache.get('gt_list')
if gt_list is None:
print('开始从数据库中读取数据')
gt_list = GoodsType.objects.filter(parent=None)
cache.set('gt_list', gt_list)
print("数据获取完成")
return render(request, 'index.html', {'gt_list':gt_list})
第一次读取结果为:
开始从缓存中查询所有商品类型
开始从数据库中读取数据
数据读取完成
第二次读取结果
开始从缓存中查询所有商品类型
数据读取完成