My model has a date field and i want to filter the model by the last 7 days.
class Count(models.Model):
task = models.ForeignKey(Task, related_name = 'counts', on_delete = models.CASCADE)
start_time = models.DateTimeField(null = True, blank = True)
end_time = models.DateTimeField(null = True, blank = True)
time_spent = models.PositiveIntegerField()
deleted = models.BooleanField(default = False)
class Meta():
ordering = ['accesses']
def __str__(self):
return f'{self.task.department} - {self.accesses.first().user} [{self.time_spent} min]'
def stamped_date(self):
if not self.start_time:
return self.accesses.first().date
return self.start_time
def users(self):
return list(set(map(lambda x: x.user, list(self.accesses.all()))))
I need to filter every count that has "stamped_date" in the last 7 days.
What i tried to do (in the model):
def daysBy(self):
return (datetime.now() - self.stamped_date()).days
to filter like this:
Count.objects.filter(daysBy__let = 7)
However, datetime.now() requires a timezone object, otherwise will throw the follwing error:
TypeError: can't subtract offset-naive and offset-aware datetimes
I'm also feeling this might not be the most correct way of achieving my goal, please correct me with a better way.
Or.. give me a way of inserting a timezone object related to the TIME_ZONE setting.