首页 > 解决方案 > FOREIGN KEY 约束在删除对象时失败

问题描述

当我要从购物车中删除产品时,它给了我错误FOREIGN KEY constraint failed

class Cart(TimeStamp):
    user = models.ForeignKey('authentication.User', on_delete=models.CASCADE, related_name='user_carts', null=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True)
    sub_total_price = models.DecimalField(max_digits=100, decimal_places=2, blank=True, null=True)
    quantity = models.PositiveIntegerField(default=1)

这是模型首先我认为问题是on_delete我将它更改为SET_NULL但它没用而且它不起作用,我试图从migrations文件夹中删除所有文件它也没有解决我的问题。这是views.py

class CartUpdateDestroyView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Cart.objects.all()
    serializer_class = CartSerializer
    permission_classes = (IsOwnerOrAdmin,)
    lookup_field = 'id'

    def get_queryset(self):
        return Cart.objects.filter(user=self.request.user)

在这个视图中,除了Destroy所有都正常工作,但我无法删除该对象。请问有什么想法吗?

标签: djangopython-3.xdjango-modelsdjango-rest-framework

解决方案


视图.py

def cart_update(request):
    product_id = request.POST.get('product_id')

    if product_id is not None:
        try:
            product_obj = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            print("Show message to user, product is gone?")
            return redirect("cart:home")
        cart_obj, new_obj = Cart.objects.new_or_get(request)
        if product_obj in cart_obj.products.all():
            cart_obj.products.remove(product_obj)
            added = False
        else:
            cart_obj.products.add(product_obj) # cart_obj.products.add(product_id)
            added = True
        request.session['cart_items'] = cart_obj.products.count()
        # return redirect(product_obj.get_absolute_url())
        if request.is_ajax(): # Asynchronous JavaScript And XML / JSON
            print("Ajax request")
            json_data = {
                "added": added,
                "removed": not added,
                "cartItemCount": cart_obj.products.count()
            }
            return JsonResponse(json_data)
    return redirect("cart:home")

模型.py

class Cart(models.Model):
user        = models.ForeignKey(User, null=True, blank=True)
products    = models.ManyToManyField(Product, blank=True)
subtotal    = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
total       = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
updated     = models.DateTimeField(auto_now=True)
timestamp   = models.DateTimeField(auto_now_add=True)
total1      = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)

objects = CartManager()

def __str__(self):
    return str(self.id)

推荐阅读