django - 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
所有都正常工作,但我无法删除该对象。请问有什么想法吗?
解决方案
视图.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)
推荐阅读
- php - Elasticsearch“你的意思是”功能
- android - ffmpeg 命令创建可共享到 Instagram 等的 mp4 视频
- java - 使用 apache Shiro 会话到期时如何重新登录?
- json - 将命令的输出转换为有效的 json?
- reactjs - Formik 和反应自动完成
- php - 我想在关联数组中搜索字符串
- github - GitHub 上的搜索结果数量从搜索到搜索发生巨大变化
- pandas - 如何从 DataFrame 中选择一列,使其具有 (n, 1) 而不是 (n,) 的形状?
- c# - 如何在 C# 中将文件从一个位置复制到另一个位置
- python - 如何将 2 个元素放入 2 个单独的列表中?