1. 后端接口设计

请求方式 : GET /cart/

请求参数: 无

返回数据: JSON 或 表单

[
    {
        "id": 9,
        "count": 3,
        "name": "华为 HUAWEI P10 Plus 6GB+64GB 钻雕金 移动联通电信4G手机 双卡双待",
        "default_image_url": "http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRcUeAHp9pAARfIK95am88523545",
        "price": "3388.00",
        "selected": true
    },
    {
        "id": 12,
        "count": 1,
        "name": "华为 HUAWEI P10 Plus 6GB+64GB 钻雕蓝 移动联通电信4G手机 双卡双待",
        "default_image_url": "http://image.meiduo.site:8888/group1/M00/00/02/CtM3BVrRdICAO_CRAAcPaeOqMpA2024091",
        "price": "3388.00",
        "selected": true
    }
]
参数 类型 是否必须 说明
id int 商品sku id
count int 数量
selected bool 是否勾选,默认勾选
name str 商品名称
default_image_url str 商品默认图片
price decimal 商品单价

2. 后端实现

在carts/serializers.py中创建序列化器

class CartSKUSerializer(serializers.ModelSerializer):
    """
    购物车商品数据序列化器
    """
    count = serializers.IntegerField(label=\'数量\')
    selected = serializers.BooleanField(label=\'是否勾选\')

    class Meta:
        model = SKU
        fields = (\'id\', \'count\', \'name\', \'default_image_url\', \'price\', \'selected\')

在carts/views.py 中修改视图,增加get方法

class CartView(APIView):
    ...

    def get(self, request):
        """
        获取购物车
        """
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录,从redis中读取
            redis_conn = get_redis_connection(\'cart\')
            redis_cart = redis_conn.hgetall(\'cart_%s\' % user.id)
            redis_cart_selected = redis_conn.smembers(\'cart_selected_%s\' % user.id)
            cart = {}
            for sku_id, count in redis_cart.items():
                cart[int(sku_id)] = {
                    \'count\': int(count),
                    \'selected\': sku_id in redis_cart_selected
                }
        else:
            # 用户未登录,从cookie中读取
            cart = request.COOKIES.get(\'cart\')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

        # 遍历处理购物车数据
        skus = SKU.objects.filter(id__in=cart.keys())
        for sku in skus:
            sku.count = cart[sku.id][\'count\']
            sku.selected = cart[sku.id][\'selected\']

        serializer = CartSKUSerializer(skus, many=True)
        return Response(serializer.data)

版权声明:本文为hzlnice原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/hzlnice/p/9393122.html