django 按时间筛选,今年,去年,上月

today = datetime.datetime.now()
1 Current year

Order.objects.filter(created_at__year=today.year)
2 Current month

Order.objects.filter(created_at__year=today.year, created_at__month=today.month)
3 Last month

last_month = today.month - 1 if today.month>1 else 12
last_month_year = today.year if today.month > last_month else today.year - 1

Order.objects.filter(created_at__year=last_month_year, created_at__month=last_month)
4 Last year

last_year = today.year - 1
Order.objects.filter(created_at__year=last_year)
5 Single Query

As last year + current year includes last month and current month, and all orders>= last_year includes current year, the query is super simple:

Order.objects.filter(created_at__year__gte=last_year)

from:[https://stackoverflow.com/questions/28101480/how-can-i-query-for-objects-in-current-year-current-month-in-django]

 

 
posted @ 2018-03-09 12:03  Jeff_blog  阅读(673)  评论(0编辑  收藏  举报