内部服务器错误:/pluscart/,app.models.Cart.MultipleObjectsReturned:get() 返回了多个购物车 - 它返回了 8

问题描述 投票:0回答:1
views.py


from django.db.models import Count
from django.shortcuts import render,redirect
from django.http import JsonResponse
from django.views import View
from . models import Product, Cart, Customer
from . forms import CustomerRegistrationFrom, CustomerProfileForm
from django.contrib import messages
from django.db.models import Q

def plus_cart(request):
    if request.method == "GET":
        prod_id=request.GET['prod_id']
        c = Cart.objects.get(Q(product=prod_id) & Q (user=request.user))
        c.quantity+=1
        c.save()
        user = request.user
        cart = Cart.objects.filter(user=user)
        amount = 0
        for p in cart:
            value = p.quantity * p.product.discounted_price
            amount = amount + value
        totalamount = amount + 40
        #print(prod_id)
        data={
            'quantity':c.quantity,
            'amount':amount,
            'totalamount':totalamount,
        }
        return JsonResponse(data)



script.js


$('.plus-cart').click(function(){
    var id=$(this).attr("pid").toString();
    var eml = this.parentNode.children[2]
    console.log("pid =",id)
    $.ajax({
        type:"GET",
        url:"/pluscart",
        data:{
            prod_id:id
        },
        success:function(data){
            console.log("data = ",data);
            eml.innerHTML = data.quantity
            document.getElementById("amount").innerText=data.amount
            document.getElementById("totalamount").innerText=data.totalamount
        }
    })
})

Internal Server Error: /pluscart/
Traceback (most recent call last):
  File "C:\Users\SIRI\OneDrive\Desktop\E-com\env\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\SIRI\OneDrive\Desktop\E-com\ec\app\views.py", line 127, in plus_cart
    c = Cart.objects.get(Q(product=prod_id) & Q (user=request.user))
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\SIRI\OneDrive\Desktop\E-com\env\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\SIRI\OneDrive\Desktop\E-com\env\Lib\site-packages\django\db\models\query.py", line 640, in get
    raise self.model.MultipleObjectsReturned(
app.models.Cart.MultipleObjectsReturned: get() returned more than one Cart -- it returned 8!
[07/May/2023 20:18:49] "GET /pluscart/?prod_id=1 HTTP/1.1" 500 77472

我尝试增加数量但显示错误

python django ajax
1个回答
0
投票

您的问题是您有一个如下所示的模型:

class Cart(models.Model):
    //Built-in id that is autogenerated in each Django model.
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.IntegerField()
    user = models.ForeignKey(User, on_delete=models.CASCADE)

因此,您将以下两个变量传递给视图:

request.user
prod_id
,因此在过滤时,您可能会获得不止一种与
Product
User
相关的产品。要解决您的问题,您应该做的不是传递到视图
product_id
您必须以这种方式传递
Cart.id
您可以过滤如下内容:

def plus_cart(request):
    if request.method == "GET":
        pk = request.GET['cart_id']
        c = Cart.objects.get(pk=pk, user=request.user)
        c.quantity+=1
        c.save(update_fields=['quantity'])
        user = request.user
        cart = Cart.objects.filter(user=user)
        amount = 0
        for p in cart:
            value = p.quantity * p.product.discounted_price
            amount = amount + value
        totalamount = amount + 40
        #print(prod_id)
        data={
            'quantity':c.quantity,
            'amount':amount,
            'totalamount':totalamount,
        }
        return JsonResponse(data)

您必须在前端确保

Cart.id
以AJAX方法发送到后端,然后您才能使其正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.