I am creating an eCommerce site and need to reduce the stock of products available when a user purchases them. This is done via views.py and without any forms involved.
I am currently doing...
product = ProductItem.objects.filter(id=4).first()
product.quantity_available -= items.get('quantity')
product.save()
My Models.py...
class ProductItem(models.Model):
OPTIONS = [
("RED","Red"),
("DBL","Dark Blue"),
("LBL","Light Blue"),
("DGR","Dark Green"),
("LGR","Light Green"),
("PNK","Pink"),
("GRY","Gray"),
("BLK","Black"),
("BRO","Brown"),
("WHT","White"),
("MAR","Marroon"),
("ORG","Orange"),
("BEG","Beige"),
("GLD","Gold"),
("SLV","Silver"),
("MLT", "MultiColour")
]
product = models.ForeignKey(Product, on_delete=models.CASCADE)
colour = models.CharField(choices=OPTIONS, default="BLK", max_length=20)
quantity_available = models.PositiveIntegerField()
def __str__(self):
return f"{self.product} -> ({self.colour})"
class Meta:
unique_together = (('product', 'colour'),)
This is my full views.py...
def save_order(request, choice):
details = request.session.get('final_order')
address = Shipping.objects.filter(pk=details.get('delivery_id')).first()
order_id = Order.objects.create(customer=request.user, address=address, total=details.get('total'), payment=choice).id
order = Order.objects.filter(id=order_id).first()
items = request.session.get('order')
pro = ProductItem.objects
for item in items:
prod = pro.filter(id=item.get('id')).first()
OrderItem.objects.create(product=prod, quantity=item.get('quantity'), user=request.user, orderNo=order)
prod.quantity_available -= items.get('quantity')
prod.save()
Where items.get('quantity')
shows the quantity of the number of items that a user has bought of that product, and session.get('final_order')
gets some related information about the order of the customer.
However, for some reason, this code doesn't seem to work. Is there any error in this?
Any help would be greatly appreciated. Thanks!