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.
I tried on the expired function but in the admin interface it always only shows 'fine' or 'expired'
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'