MBsola
MBsola

Reputation: 28

Functions inside a Django model

Is it possible to write custom functions inside a Django model? And if it is, how can I do it properly. I'm currently doing a practice project of an ecommerce, and I want to change a boolean field value based on the value of an integer field. I currently have this:

class Product(Model):
   name = CharField(max_length=64)
   desc = CharField(max_length=256)
   price = DecimalField(decimal_places=2, max_digits=6)
   available = BooleanField(default=True)
   quantity = IntegerField()
   category = ManyToManyField(Category)

   def availability(self):
       if self.quantity == 0:
           self.available = False
           self.save()
       return self.available

   def __str__(self):
       return self.name

I know that I'm not calling the function, but I want that to be called once the product is updated even on the admin panel, is that possible to do?

And I'm not really confident about that return in the function, I don't feel like that is correct.

Thanks in advance.

Upvotes: 0

Views: 64

Answers (1)

Swapnil Chopra
Swapnil Chopra

Reputation: 676

Yes, this can be achieved in two ways, using the save method of the model class or by using save_model method of admin class.

This is a demonstration by using save() method of model class

class Product(Model):
   name = CharField(max_length=64)
   desc = CharField(max_length=256)
   price = DecimalField(decimal_places=2, max_digits=6)
   available = BooleanField(default=True)
   quantity = IntegerField()
   category = ManyToManyField(Category)

   def __str__(self):
       return self.name

   def save(self, *args, **kwargs):
       if self.quantity == 0:
           self.available = False
       super().save(*args, **kwargs)

Upvotes: 1

Related Questions