smith
smith

Reputation: 373

How can add the data in db field which already exists

I am trying to add the data in main_storage table but when I save the record it show the error

 failed unsupported operand type(s) for +: 'DeferredAttribute' and 'int'   

In Main_Storage productId is foreign key I want to add the data according to the foreign key but it show the error

            try:
            data = self.request.POST.get
            orderView = GatePass(
                fault=data('fault'),
                remarks=data('remarks'),
                order_id=order_Id
            )
            dbItem = Order.objects.get(id=order_Id)
            items = dbItem.orderProduct.quantity
            order_request = OrderRequest.objects.get(pk=orderId)
            faultItem = orderView.fault
            if int(faultItem) >= items:
                return HttpResponse('error')
            else:
                order_request.order.orderProduct.quantity -= int(faultItem)
                Main_Storage.objects.filter(
                    product_id=productId
                ).update(
                    quantity=F('quantity') + order_request.order.orderProduct.quantity
                )
                order_request.order.orderProduct.quantity = int(faultItem)
                order_request.order.orderProduct.save()
                orderView.save()

Upvotes: 2

Views: 289

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can update the Main_Storage object with:

from django.db.models import F

Main_Storage.objects.filter(
    product_id=productId
).update(
    quantity=F('quantity') + order_request.order.orderProduct.quantity
)

This will work if we know that there is already one Main_Storage record for this product_id.

If we do not know that, we can work with .get_or_create(…) [Django-doc]:

from django.db.models import F

qty = order_request.order.orderProduct.quantity

obj, created = Main_Storage.objects.get_or_create(
    product_id=productId,
    defaults={'quantity': qty}
)
if not created:
    obj.quantity = F('quantity') + qty
    obj.save()

Upvotes: 3

Related Questions