获取所有不足一个月的项目
有没有办法在Django中获取所有日期在一个月之前的对象呢?
类似于下面这样的:
items = Item.objects.filter(less than a month old).order_by(...)
3 个回答
1
items = Item.objects.filter(created_date__gte=aMonthAgo)
这里的 aMonthAgo 是通过日期时间和时间间隔来计算的。
3
这样做:
from datetime import datetime, timedelta
def is_leap_year(year):
if year % 100 == 0:
return year % 100 == 0
return year % 4 == 0
def get_lapse():
last_month = datetime.today().month
current_year = datetime.today().year
#is last month a month with 30 days?
if last_month in [9, 4, 6, 11]:
lapse = 30
#is last month a month with 31 days?
elif last_month in [1, 3, 5, 7, 8, 10, 12]:
lapse = 31
#is last month February?
else:
if is_leap_year(current_year):
lapse = 29
else:
lapse = 30
return lapse
last_month_filter = datetime.today() - timedelta(days=get_lapse())
items = Item.objects.filter(date_created__gte=last_month_filter)
这样可以处理我能想到的所有情况。
59
你对“一个月”的定义是什么?是30天?还是31天?除此之外,这段代码应该能帮到你:
from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
items = Item.objects.filter(my_date__gte=last_month).order_by(...)
这段代码利用了gte这个字段查找功能。