Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading