在web項目中(尤其是管理端)經常遇到的一種場景是根據指定時間段篩選數據。比如,根據發佈時間(publish_time)篩選,根據添加時間篩選等。本文主要介紹django中的時間段查詢應該如何處理。
我們以文章(Article)發佈時間(publish_time)爲例。
注意:這裏發佈時間(publish_time)的字段類型應該是date或者datetime,否則不在本文討論範圍。
now = datetime.datetime.now()
start = datetime.datetime(2017,1,1)
1、大於某個時間(gt)
Aticle.objects .filter(publish_time__gt=now)
2、大於等於某個時間(gte)
Aticle.objects .filter(publish_time__gte=now)
3、小於某個時間(lt)
Aticle.objects .filter(publish_time__lt=now)
4、小於等於某個時間(lte)
Aticle.objects .filter(publish_time__lte=now)
5、查詢時間段(range)
Aticle.objects .filter(publish_time__range=(start,now))
6、查詢某年(year)
Aticle.objects .filter(publish_time__year=now.year)
7、查詢某月(month)
Aticle.objects .filter(publish_time__month=now.month)
8、查詢某天(day)
Aticle.objects .filter(publish_time__day=now.day)
9、查詢星期幾(week_day)
Aticle.objects .filter(publish_time__week_day=1)
本文分享自微信公衆號 - 飛槳PPDB(Tsing_Liu)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。