Django --- 自连接和缓存

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})

第一次读取结果为:
开始从缓存中查询所有商品类型
开始从数据库中读取数据
数据读取完成

第二次读取结果
开始从缓存中查询所有商品类型
数据读取完成
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值