This is a very naive approach to the issue and it's a race condition away from being a day+ debugging nightmare for you.
def increase_stock_quantity(self, amount):
self.quantity_in_stock += amount
self.save()
def decrease_stock_quantity(self, amount):
if amount > self.quantity_in_stock:
raise ValueError('The Amount is Larger Than the Quantity in Stock')
self.quantity_in_stock -= amount
self.save()
- use locks (
.select_for_update()) - (or) use query set
self.objects.filter(id=self.id).update(quantity_in_stock=F('quantity_in_stock') + 1)
Also make sure you wrap this inside a transaction.
def save(self, *args, **kwargs):
if self.issued_quantity > self.item.quantity_in_stock:
raise ValidationError('Issued Quantity Exceeds Available Quantity')
self.item.decrease_stock_quantity(self.issued_quantity)
super(IssuedItem, self).save(*args, **kwargs)
- The
ifshould be moved toclean(). self.item.decrease_stock_quantity(self.issued_quantity)in the save feels very, VERY wrong! Not to mention a HUGE side-effect for something that shouldn't be happening.super(IssuedItem, self).save(*args, **kwargs)missing areturnand removeIssuedItem, selffromsuper().
While i'mI'm at it, install and run ruff.