追踪物品数量&价格在购物车

时间:2016-03-22 19:10:28

标签: python django

我在Django应用程序中有一个购物车。您可以在购物车中添加和删除商品。

我终于有了工作的逻辑。通过很多麻烦拍摄它将添加购物车中的物品并将其删除。每次从购物车中添加或删除商品时,都会重新计算价格。

但仅限购物车中的第一个产品。购物车中的顶级产品根据其数量重新调整价格。其余产品可以增加或减少,但总成本始终保持不变。我不清楚这个问题是否在视图或模型中的逻辑中。

enter image description here

谢谢,

models.py

class Cart(models.Model):
    user = models.ForeignKey(User)
    active = models.BooleanField(default=True)
    order_date = models.DateField(null=True)
    payment_type = models.CharField(max_length=100, null=True)
    payment_id = models.CharField(max_length=100, null=True)

    def __unicode__(self): 
            return "%s" % (self.user)

    def remove_from_cart(self, book_id):
        book = Book.objects.get(pk=book_id)
        try:
            preexisting_order = BookOrder.objects.get(book=book, cart=self)
            if preexisting_order.quantity > 1:
                preexisting_order.quantity -= 1
                preexisting_order.save()
            else:
                preexisting_order.delete()
        except BookOrder.DoesNotExist:
            pass

views.py

@login_required
def add_to_cart(request,book_id):
    book = get_object_or_404(Book, pk=book_id)
    cart,created = Cart.objects.get_or_create(user=request.user, active=True)
    order,created = BookOrder.objects.get_or_create(book=book,cart=cart)
    order.quantity += 1
    order.save()
    messages.success(request, "Cart updated!")
    return redirect('cart')


def remove_from_cart(request, book_id):
    if request.user.is_authenticated():
        try:
            book = Book.objects.get(pk = book_id)
        except ObjectDoesNotExist:
            pass 
        else:
            cart = Cart.objects.get(user = request.user, active = True)
            cart.remove_from_cart(book_id)
        return redirect('cart')
    else:
        return redirect('index')

def cart(request):
    if request.user.is_authenticated():
        cart = Cart.objects.filter(user=request.user.id, active = True)
        orders = BookOrder.objects.filter(cart=cart)
        total = 0
        count = 0
        for order in orders:
            total += (order.book.price * order.quantity)
            count += order.quantity
            context = {
            'cart': orders,
            'total': total,
            'count': count,
            }
            return render(request, 'store/cart.html', context)
        else:
            return redirect('index')

0 个答案:

没有答案