I have a model called Products. This model has values like this
JavaScript
x
6
1
class Product(models.Model):
2
title = models.CharField(max_length=70, null=True, blank=True)
3
producent = models.CharField(max_length=40, null=True, blank=True)
4
stock = models.PositiveIntegerField(default=0, null=True, blank=True)
5
display = models.BooleanField(null=True, blank=True, default=True)
6
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
JavaScript
1
2
1
Product.objects.filter(display=True)
2
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:
JavaScript
1
4
1
if product.stock==0:
2
product.display = False
3
product.save()
4
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.