如何在接下来的x个月内将查询集过滤到日期?

时间:2014-10-14 15:54:05

标签: django django-models django-queryset

我有一个名为Post的模型,带有属性日期。

我想过滤查询集,以便仅在接下来的x个月内检索帖子。例如接下来的3个月

2 个答案:

答案 0 :(得分:0)

看看range。构建日期并传递给QuerySet。 Relevant SO question for reference

答案 1 :(得分: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())])

<强>参考   - How to increment datetime by custom months in python without using library   - Django database query: How to filter objects by date range?