我有一个名为Post的模型,带有属性日期。
我想过滤查询集,以便仅在接下来的x个月内检索帖子。例如接下来的3个月
答案 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?