Django ManyToManyField 对象自动保存自身

Django ManyToManyField object automatically saves itself

我正在尝试使用 Django 创建一个电子商务网站。我将 orderProducts 作为 Cart 对象的 ManyToMany 字段。问题是为什么每当我创建一个 OrderProduct 对象时,任何现有的 Cart 都会自动保存 orderProduct 本身。这是我的模型:

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.IntegerField(default=0)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    post_date = models.DateTimeField('post date:', default=timezone.now)

    def __str__(self):
        return self.name

    def add_to_cart_url(self):
        return reverse("add_to_cart", kwargs={
            'product_id' : self.pk
        })


class OrderProduct(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    product = models.ForeignKey(Product,on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return self.product.name

    def delete_from_cart_url(self):
        return reverse("delete_from_cart", kwargs={
            'product_name' : self.product.name
        })


class Cart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    products = models.ManyToManyField(OrderProduct)

    def __str__(self):
        return self.user.username

这是add_to_cart函数,即使我注释掉cart.products.add代码,OrderProduct仍然被添加到购物车。

def add_to_cart(request,product_id):
    product = get_object_or_404(Product,pk=product_id)
    order_product,created = OrderProduct.objects.get_or_create(product=product,user=request.user)
    cart_qs = Cart.objects.filter(user=request.user)
    if cart_qs.exists():
        cart = cart_qs[0]
        if cart.products.filter(product__name=product.name).exists():
            order_product.quantity += 1
            order_product.save()
        else:
            return redirect("cart")
            #cart.products.add(order_product)
        return redirect("cart")
    else:
        cart = Cart.objects.create(user=request.user)
        #cart.products.add(order_product)
        return redirect("products")

这是购物车视图

@login_required(login_url='/login/')
def cart(request):
    # order_product_list = OrderProduct.objects.order_by('-product__price')
    cart,created = Cart.objects.get_or_create(user=request.user)
    order_product_list = cart.products.all()
    order_product_list = OrderProduct.objects.order_by('-product__price')
    total = 0
    for order_product in order_product_list:
        total += order_product.product.price * order_product.quantity

    context = {
        'products' : order_product_list,
        'total' : total,
    }

    return render(request,'login/cart.html',context)

没错,你的错误就在这里

order_product_list = OrderProduct.objects.order_by('-product__price')

在那里,您可以用所有 OrderProduct 覆盖您的产品列表,无论它们是否属于当前购物车。

你应该做的不是那样

order_product_list = cart.products.order_by('-product__price')