简体   繁体   中英

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. Django will not automatically run save every time the code runs, this would be very bad for performance.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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