Skip to content
Advertisement

Auto update model value based on another value in this model django

I have a model called Products. This model has values like this

class Product(models.Model):
    title       = models.CharField(max_length=70, null=True, blank=True)
    producent   = models.CharField(max_length=40, null=True, blank=True)
    stock       = models.PositiveIntegerField(default=0, null=True, blank=True)
    display     = models.BooleanField(null=True, blank=True, default=True)

How can I change display to be False if stock is equal to 0 automatically, so when client buys last product in store display value will change from True to False and

Product.objects.filter(display=True)

will result in products that I want to show or are in stock.

I know that I can simply chain .filter() but I wonder if I can do in an elegant way

Advertisement

Answer

For what you said I think you have a view to decrease stock value

Add this logic to your view, after update the stock value:

if product.stock==0:
    product.display = False
    product.save()

Considering that your view (used to decrease stock value) already instantiated the target “product”. If that don’t help you, please, post your view.py, to give us more information.

Advertisement