将产品添加到购物车Django Rest框架

时间:2019-03-07 00:53:14

标签: django django-rest-framework

如何使用django rest框架建立将产品添加到购物车的端点?我到处搜索,找不到。 你能帮我吗?

这是我的产品。浏览量:

matrix

serializers.py

class ProductDetail(generics.RetrieveAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer


class AddProduct(ProductDetail, ListCreateApiView):
    serializer_class = AddToCartSerializer

    @require_POST
    def get(self, request):
        cart_obj = Cart.objects.get_or_new(request)
        product_id = request.POST.get('product_id')
        qs = Product.objects.filter(id=product_id)
        if qs.count() == 1:
            product_obj = qs.first()
            if product_obj not in cart_obj.products.all():
                cart_obj.products.add(product_obj)
            else:
                cart_obj.products.remove(product_obj)
            request.session['cart_items'] = cart_obj.products.count()
        return Response(status=status.HTTP_200_OK, data={'message': 'Product has been added to cart'})

1 个答案:

答案 0 :(得分:0)

我写了这个函数,它起作用了。但是我无法控制要添加到购物车中的产品数量

class ProductDetail(generics.RetrieveAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer


class AddProduct(ProductDetail, viewsets.ModelViewSet):

    @action(detail=True, methods=['post'])
    def add_to_cart(self, request, pk):
        cart_obj = Cart.objects.get_or_new(request)
        product_id = pk
        qs = Product.objects.filter(id=product_id)
        if qs.count() == 1:
            product_obj = qs.first()
            if product_obj not in cart_obj.products.all():
                cart_obj.products.add(product_obj)
            else:
                cart_obj.products.remove(product_obj)
            request.session['cart_items'] = cart_obj.products.count()
        return Response(status=status.HTTP_200_OK, data={'message': 'Product has been added to cart'})