I have model like this
class Product(models.Model):
name = models.CharField(max_length=150)
stock = models.IntegerField()
cogs = models.IntegerField()
def __str__(self):
return f"{self.name}"
class Transaction(models.Model):
customer = models.ForeignKey(User, on_delete=models.CASCADE)
product = models.ManyToManyField(Product)
purchase_date = models.DateField(auto_now_add=True)
quantity = models.IntegerField()
total = models.IntegerField(blank=True)
def save(self, *args, **kwargs):
self.total = self.quantity * self.product.cogs
super().save(self, *args, **kwargs)
def __str__(self):
return f"{self.customer}"
my question is
How to make Product attribute in this case stock will be dynamically calculated when there is transaction input.
Every input in transaction will deduct product.stock which is product.stock - transaction.quantity
I try to automatically calculate product.stock when there is input in transaction