Django freezer app - Checking a time delta

I am working on a project for organizing a freezer. Therefore I added a model called 'ShoppingItem'. It has an 'best before' date. Now I want to check three things via a function:

Is the food expired? Is the food fine? Or is the food 'critical' (3 days before expiring)

This is my whole models.py It includes the model itself and two functions.

enter image description here

enter image description here

I tried on the expired function but can't come up with a solution

You have an error in your elif condition. You passed

def expired(self):
    if self.best_before_date > datetime.date.today():
        return 'fine'
    elif self.best_before_date >= datetime.date.today() and
            self.best_before_date >= datetime.date.today() + datetime.timedelta(days=3):
        return 'critical'
    else:
        return 'expired'

But correct is self.best_before_date <= datetime.date.today() + datetime.timedelta(days=3) because you need date more than today, but less or equal than today + 3 days.

I think this is the correct logic:

def expired(self):
    three_days_before = datetime.date.today() - datetime.timedelta(days=3)
    if self.best_before_date < three_days_before:
        return 'fine'
    elif three_days_before <= self.best_before_date <= datetime.date.today():
        return 'critical'
    # after expiration date
    else:
        return 'expired'

Back to Top