Home > Software design >  Django freezer app - Checking a time delta
Django freezer app - Checking a time delta

Time:01-20

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.

model ShoppingItem

function 'expired'

I tried on the expired function but in the admin interface it always only shows 'fine' or 'expired'

admin interface

CodePudding user response:

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.

CodePudding user response:

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'

  • Related