Vepa Orazov
Vepa Orazov

Reputation: 39

in django models.py how to make remain quantity column of item table change automatically?

class Item(models.Model):
    name=models.CharField(max_length=100)
    price=models.DecimalField(max_digits=6, decimal_places=2)
    quantity=models.IntegerField(default=0)
    sold=models.IntegerField(default=0)
    qtt=0
    def countremain(self):
        qtt=self.quantity-self.sold
        return qqt
    remain=models.IntegerField(qqt)

in admin page I can change manually remain value, but I want to make it automatically. what I have to change or add to the code above? Please help. Thanks in advance!

Upvotes: 1

Views: 303

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

What you're trying to do is called "denormalization" - if the remain value depends on quantity and sold, you theoretically shouldn't store it in the database (else you may have inconsistent data).

If you still really want to do this, you have to make sure this value is updated by each and any piece of code that touch either quantity or sold.

The safest way would be a database level trigger (which depends on your db vendor, and is neither a Django nor a Python question actually xD).

Another - less safe - solution is to recompute the value in the model's save() method:

def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
    self.remain = self.countremain()
    if update_fields:
        # could be either a tuple or list so we make sure
        # it's a list 
        update_fields = list(update_fields) + ["remain"]  
    super(Item, self).save(force_insert, force_update, using, update_fields)

Note that this isn't really safe since it won't be triggered by Queryset.update(...) - and of course won't be triggered by any other db client.

Upvotes: 2

Related Questions