简体   繁体   English

Django model 字段不是动态的

[英]Django model fields not dynamic

I have this in my models.我的模型中有这个。

class School(models.Model):
    subscribed = models.BooleanField(default=True)
    invoice_date = models.DateField()
    remaining_days = models.IntegerField(default=30)
    
    def save(self,*args,**kwargs):
        self.remaining_days = (self.invoice_date  - date.today()).days
        if self.invoice_date <= date.today():
            self.subscribed=False
        else:
            self.subscribed=True
        return super().save(*args,**kwargs)

The problem is the remaining days do not change dynamically.问题是剩余天数不会动态变化。 I thought it would when I was coding this.当我编码时,我认为它会。 How can I make it change each new day???我怎样才能让它改变每一天???

The save method will trigger once every time you update the model.每次更新 model 时都会触发一次保存方法。 Django will not automatically run save every time the code runs, this would be very bad for performance. Django 不会在每次代码运行时自动运行保存,这对性能非常不利。

What you want is probably not to use a save method to automatically do this for you.您想要的可能不是使用保存方法自动为您执行此操作。 I would say you need a scheduled operation that each day runs at a certain time and goes through the instances updating their remaining days.我会说你需要一个每天在特定时间运行的计划操作,并通过实例更新它们的剩余天数。

Nevertheless, the remaining days seem to be a calculated field.然而,剩余天数似乎是一个计算字段。 Maybe you don't need it stored in the database, since from knowing which day it is and what the invoice date is, every time you want you can just go to the models and do the calculation.也许您不需要将它存储在数据库中,因为从知道它是哪一天以及发票日期是什么,每次您想要您只需 go 到模型并进行计算即可。 A queryset could filter all the interested instances for you without the necessity of updating the remaining days every day.查询集可以为您过滤所有感兴趣的实例,而无需每天更新剩余的天数。

School.objects.filter(invoice_date__lte=datetime.now()-timedelta(days=5))

This way you can always see which ones are near the deadline without having to store the calculated field.这样您就可以随时查看哪些接近截止日期,而无需存储计算的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM