将整数更改保存到数据库中的模型错误

时间:2018-07-12 18:30:44

标签: python django

我正在尝试增加添加数量到我添加到购物车中的产品的可能性。我在产品模型中添加了一个integerfield,用作占位符(希望在结帐后将其重置)。我不知道这是否是执行此操作的最佳方法,但我认为这可能有效哈哈:-) 当我要保存数量时,在终端上可以正常打印,它会出现以下错误。如何避免这种情况?

AttributeError at /scan/stock/

'int' object has no attribute 'save'

Request Method:     POST
Request URL:    http://localhost:8000/scan/stock/
Django Version:     1.11
Exception Type:     AttributeError
Exception Value:    

'int' object has no attribute 'save'

我不知道为什么数量不能以这种方式保存到数据库中...

    def scan_to_cart(request):
        form = forms.ScanSessionForm()
        if request.method == 'POST':
            product = None
            barcode = request.POST.get('barcode_input')
            amount  = request.POST.get('amount_input')
            queryset = Child.objects.filter(product_id_code=barcode)
            if queryset.exists():
                try:
                    # the queryset is already filtered by the barcode
                    # now we apply an extra filter to check if this user has the product
                    product = queryset.get(user=request.user)
                except Child.DoesNotExist:
                    # here we are sure this product exists, but this user doesnt have it in the stock.
                    messages.error(request, 'I can\'t find any inventory with this barcode')
            else:
                # here we know this product doesnt exist
                messages.error(request, 'I can\'t find any inventory with this barcode')
            if product is not None:
                form = forms.ScanSessionForm(request.POST, instance=product)
                if form.is_valid():

                    product_obj = product.id
                    cart_obj, new_obj = Cart.objects.new_or_get(request)
                    products = cart_obj.products.all()
                    cart_obj.products.add(product_obj)

# It's about this section of code
                    quantity = product.session_amount
                    print (quantity)
                    quantity += int(amount)
                    print (quantity)
                quantity.save()

                messages.success(request, '%s - %s was successfully added to cart' % (product.product_name, product.sku))   
                return HttpResponseRedirect('/scan/stock/')
    else:
        form = forms.ScanSessionForm()
    return render(request, 'stockscan/scan_to_cart.html', {'form': form})

1 个答案:

答案 0 :(得分:1)

您正在尝试保存quantity的{​​{1}}。您可能想做的是先将新数量归于产品,然后保存产品:

int

甚至更快:

quantity = product.session_amount
quantity += int(amount)
product.session_amount = quantity
product.save()