Home > front end >  Django model fields not dynamic
Django model fields not dynamic

Time:01-28

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

CodePudding user response:

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.

  •  Tags:  
  • Related