Home > Software design >  how to change the Model field value with logic to time
how to change the Model field value with logic to time

Time:04-12

Say I have a model named Quote

class Quote(models.Model):
    # date_validity will have persistent data like this 2023-11-30 15:00
    date_validity = models.CharField(max_length=100, blank=True)
    quote_status = models.CharField(
        max_length=150, default='active')

So I need to set quote_status expired if data_validity meets the current time, If validity is 2 days later from now then the quote should expire if validity time is over.

How can I manage this automatically? As far as I know self.save() method does not trigger automatically. So any suggestions to solve this?

I guess this is not possible until we call a function periodically like with celery. Is there other way to do?

CodePudding user response:

Please use a DateTimeField [Django-doc], not a CharField to store a timestamp. As for the status, you should not store this in the model. You can determine this when necessary, for example with a property, or with a .annotate(…) [Django-doc] to check the status.

Indeed, you can define a model with:

from django.utils.timezone import now
from datetime import timedelta

class Quote(models.Model):
    created = models.DateTimeField()

    @property
    def status(self):
        return 'active' if self.created >= now()-timdelta(days=2) else 'expired'

and you can for example retrieve all acive and expired quotes with:

from django.db.models.functions import Now
from datetime import timedelta

active = Quote.objects.filter(created__gte=Now()-timedelta(days=2))
expired = Quote.objects.filter(created__lt=Now()-timedelta(days=2))
  • Related