最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

run one time for Django model calculated property - Stack Overflow

programmeradmin8浏览0评论
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
Add a comment  | 

1 Answer 1

Reset to default -1

Found 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)
发布评论

评论列表(0)

  1. 暂无评论