class Company_Car(models.Model):
@property
def days_left(self):
print("RUNNED PROPERTY")
if self.date_valid is not None and self.date_valid >= datetime.datetime.now().date():
return (self.date_valid - datetime.datetime.now().date()).days
added = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
company = models.ForeignKey(Company, on_delete=models.DO_NOTHING)
date_valid = models.DateField(null=True, blank=True)
Each time when i ask this property for same record it executes and it's not good
My goal - property should run only once and return calculated data
How it can done?
class Company_Car(models.Model):
@property
def days_left(self):
print("RUNNED PROPERTY")
if self.date_valid is not None and self.date_valid >= datetime.datetime.now().date():
return (self.date_valid - datetime.datetime.now().date()).days
added = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
company = models.ForeignKey(Company, on_delete=models.DO_NOTHING)
date_valid = models.DateField(null=True, blank=True)
Each time when i ask this property for same record it executes and it's not good
My goal - property should run only once and return calculated data
How it can done?
Share Improve this question asked Mar 23 at 7:23 YuretzYuretz 1192 silver badges12 bronze badges 2- 2 I don't really see why running this property multiple times is a problem: calculations with dates are (almost) instant and take almost no processing power. – willeM_ Van Onsem Commented Mar 23 at 11:25
- I thought the same, but i use this property in template render with queryset with 150+ records, so execution time takes more than 2 seconds – Yuretz Commented Mar 23 at 13:54
1 Answer
Reset to default -1Found a solution: there is a build-in decorator @cached_rpoperty
from django.utils.functional import cached_property ## HERE
class Company_Car(models.Model):
@cached_property ### AND HERE
def days_left(self):
print("RUNNED PROPERTY")
if self.date_valid is not None and self.date_valid >= datetime.datetime.now().date():
return (self.date_valid - datetime.datetime.now().date()).days
added = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
company = models.ForeignKey(Company, on_delete=models.DO_NOTHING)
date_valid = models.DateField(null=True, blank=True)