I have a model called Post with an attribute date.
I want to filter the queryset so that I retrieve posts only in the next x months. e.g. next 3 months
I have a model called Post with an attribute date.
I want to filter the queryset so that I retrieve posts only in the next x months. e.g. next 3 months
Take a look at range
. Build the date and pass to the QuerySet. Relevant SO question for reference.
from datetime import datetime
import calendar
def add_months(sourcedate, months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month / 12
month = month % 12 + 1
day = min(sourcedate.day, calendar.monthrange(year,month)[1])
return datetime.date(year, month, day)
today = datetime.today()
table_name.objects.filter(date__range=[str(today.date()), str(add_months(today, 3).date())])
Reference - How to increment datetime by custom months in python without using library - Django database query: How to filter objects by date range?