Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Queryset: filter by weeks

Tags:

python

django

I am trying to filter a query by weeks. It will return jobs if the jobs report_by_date is within a week.

Job.objects.filter((report_by_date-datetime.today()).days <= 7)
like image 784
user3972986 Avatar asked Nov 23 '15 10:11

user3972986


People also ask

How do I filter query objects by date range in Django?

This can be done via the datetime. combine method as above, but I've found that it can be a bit simpler to merely accommodate the discrepancy by adding a timedelta(days=1) to either the start/end date in the range -- depending on the problem. So Example.

What is Select_related in Django?

Django offers a QuerySet method called select_related() that allows you to retrieve related objects for one-to-many relationships. This translates to a single, more complex QuerySet, but you avoid additional queries when accessing the related objects. The select_related method is for ForeignKey and OneToOne fields.


1 Answers

You can create a datetime for one week ago, then filter all jobs after that.

from datetime import datetime, timedelta
one_week_ago = datetime.today() - timedelta(days=7)
jobs = Job.objects.filter(report_by_date__gte=one_week_ago)
like image 188
Alasdair Avatar answered Sep 23 '22 11:09

Alasdair