from django.shortcuts import render from rest_framework.views import APIView from serializers import CartSerializers from django_redis import get_redis_connection from rest_framework.response import Response from rest_framework import status
from django.shortcuts import render from rest_framework.views import APIView from .serializers import CartSerializers, SKUCartSerializers from django_redis import get_redis_connection from rest_framework.response import Response from rest_framework import status from goods.models import SKU
# 展示购物车商品 defget(self,request): # 用户是否登录 user = request.user if user and user.is_authenticated: # 查询哪些数据(SKU) 返回的是什么类型 json ---> 序列化器作一个序列化输出 # 从 redis里面拿 sku_id redis_conn = get_redis_connection("carts") # 获取数据 cart_redis_dict = redis_conn.hgetall('cart_%d' % user.id) # 获取 set 勾选的数据 selecteds = redis_conn.smembers('selected_%d' % user.id)
cart_dict = {} # for i in cart_redis_dict.key() : for sku_id_bytes, count_bytes in cart_redis_dict.items(): cart_dict[int(sku_id_bytes)] = { 'count': int(count_bytes), 'selected': sku_id_bytes in selecteds } skus = SKU.objects.filter(id__in=cart_dict.keys())
for sku in skus: # 临时添加属性 # sku.count = cart_redis_dict[sku.id]['count'] sku.count = cart_dict[sku.id]['count'] sku.selected = selecteds[sku.id]['selected'] # sku.selected = selecteds ser = SKUCartSerializers(skus, many=True) return Response(ser.data)