如何在Django Rest API中执行批量更新

时间:2019-11-02 03:04:57

标签: django django-models django-rest-framework django-templates

表结构

cart_id, product_id, quantity,customer_id

视图

class CartUpdateView(generics.UpdateAPIView):
    queryset = models.Cart.objects.all()
    serializer_class = CartSerializer

    def put(self, request, *args, **kwargs):
        data = request.DATA
        serializer = CartSerializer(data=data, many=True)

        if serializer.is_valid():
            serializer.save()
            return Response(status=HTTP_200_OK)
        else:
            return Response(status=HTTP_400_BAD_REQUEST)

序列化器

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ('cart_id', 'quantity', 'customer_id', 'product_id')

型号

class Cart(models.Model):
    cart_id = models.IntegerField()
    product_id = models.IntegerField()
    quantity = models.IntegerField()
    customer_id=models.IntegerField()

我正在尝试使用数据更新购物车

{
    [cart_id:1, product_id:3, quantity:5,customer_id:2],
    [cart_id:2, product_id:4, quantity:2,customer_id:2],
    [cart_id:3, product_id:5, quantity:1,customer_id:2],
    [cart_id:4, product_id:8, quantity:1,customer_id:2],
}

但这不能按预期工作。到目前为止,我只进行了单行更新。有没有一种方法可以执行批量更新。我需要重写任何方法吗?!

0 个答案:

没有答案