django-获取购物车商品数量-redis

视图函数views.py中

from django_redis import get_redis_connection  # 连接redis
class IndexView(View):
    '''首页'''
    def get(self, request):
        '''显示首页'''
        # 获取缓存数据
        context = cache.get('index_page_data')

        if context is None:
            print('设置缓存')
            # 获取商品的种类信息
            types = GoodsType.objects.all()

            # 获取首页轮播商品信息
            goods_banners = IndexGoodsBanner.objects.all().order_by('index')

            # 获取首页促销活动信息
            promotion_banners = IndexPromotionBanner.objects.all().order_by('index')

            # 获取首页分类商品展示信息
            for type in types:  # GoodsType
                # 获取type种类首页分类商品的图片展示信息
                image_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=1).order_by('index')
                # 获取type种类首页分类商品的文字展示信息
                title_banners = IndexTypeGoodsBanner.objects.filter(type=type, display_type=0).order_by('index')

                # 动态给type增加属性,分别保存首页分类商品的图片展示信息和文字展示信息
                type.image_banners = image_banners
                type.title_banners = title_banners

            # 组织模板上下文
            context = {'types': types,
                       'goods_banners': goods_banners,
                       'promotion_banners': promotion_banners}
            # 设置缓存
            # key  value timeout
            cache.set('index_page_data', context, 3600)

        # 获取用户购物车中的商品数目
        # 获取用户登录信息
        user = request.user
        # 默认购物车数量为0
        cart_count = 0
        # 判断用户是否登录
        if user.is_authenticated():
            # 用户已登录
            conn = get_redis_connection('default')
            cart_key = 'cart_%d'%user.id
            cart_count = conn.hlen(cart_key)
        # 更新数据信息
        context.update(cart_count=cart_count)
        return render(request, 'index.html', context)

模板文件index.html

 {# 购物车 #}
            <div class="guest_cart fr">
                <a href="#" class="cart_name fl">我的购物车</a>
                <div class="goods_count fl" id="show_count">{{ cart_count }}</div>
            </div>

 设置cart_key的数据

hmset cart_2 1 3 2 5

猜你喜欢

转载自www.cnblogs.com/yifengs/p/11624485.html