Reputation: 1556
Im working on a Django project and I have to make a query that returns all my record that are active at the moment. The query must be between(startdate, startdate + duration)
I got this query so far, but I don't know how to query startdate + duration < datetime.now()
View:
def home(request):
active_tasks = Task.objects.all().filter(start_time__lte=datetime.now())
context = {'active_tasks' : active_tasks}
return render(request, "main/home.html", context)
Task model:
class Task(models.Model):
start_time = models.DateTimeField(default=datetime.now())
duration = models.IntegerField(default=10)
Upvotes: 0
Views: 658
Reputation: 25539
Your code has several defects. First, it's not clear for us what unit does duration
have, days, months, years, minutes?
I assume you were using days, but you couldn't query that because you need to convert start_time + duration
to datetime and treat it as end time for each record, which is not possible in single query. As @solarissmoke mentioned, you should store the end_time
instead. You could keep the duration
field if you want, but you could also use a property method to calculate it.
Also, your field definition start_time = models.DateTimeField(default=datetime.now())
would not work, because the default time would only be evaluated once when django starts(when the model is loaded). It's a common mistake that new django developers make. You should change it to:
start_time = models.DateTimeField(default=datetime.now)
This case, datetime.now
would be treated as a function object and be called every time you create a new object, which is what you want. Note that django has the built in flag to do that: auto_now_add
.
Check this SO answer on more detailed explanation.
Upvotes: 1