BLOG
Enjoy when you can, and endure when you must.
MAR 05, 2013/Django
Django Model中基于时间的筛选(续)

在昨天的写《Django Model中基于时间的筛选》一文中,我写到可以使用published_date__range来提取某个时间段内的所有数据,那就想到这样一个需求:如果要筛选出某月内的所有数据应该怎么做呢?如果采用写死的方式,如:

start_date = datetime.date(2012, 12, 1)

end_date = datetime.date(2012, 12, 31)

blog.objects.filter(published_date__range=(start_date, end_date))

这样的局限在于如果月中的天数是不定的,我们必须基于给定的月份找到其头和尾。这里可以利用Python的内置模块calendar来达到该目的:

now = datetime.datetime.now()

# get the first day and the last day of this month.

last_day_of_this_month = calendar.monthrange(now.year, now.month)[1]

start_date = datetime.date(now.year, now.month, 1)

end_date = datetime.date(now.year, now.month, last_day_of_this_month)

blog.objects.filter(published_date__range=(start_date, end_date))

COMMENTS
LEAVE COMMNT