0

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

user700077
  • 93
  • 2
  • 9

2 Answers2

0

Take a look at range. Build the date and pass to the QuerySet. Relevant SO question for reference.

Community
  • 1
  • 1
Celeo
  • 5,583
  • 8
  • 39
  • 41
0
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?

Community
  • 1
  • 1
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38