我需要找到创建的对象总数
1. current year
2. current month
3. last month
4. last year
我是这样想的
this_year = datetime.now().year
last_year = datetime.now().year -1
this_month = datetime.now().month
last month = (datetime.today() - timedelta(days=30)).month
像这样使用
Order.objects.filter(created_at__month=this_month)
问题是
- 我想要的 last_month 是日历月而不是 30 天前
- 我不确定 created_at__month=this_month 是否匹配当前月份或上一年的同月
- 是否可以在单个查询中获取所有计数
最佳答案
today = datetime.datetime.now()
1 当前年份
Order.objects.filter(created_at__year=today.year)
2 当前月份
Order.objects.filter(created_at__year=today.year, created_at__month=today.month)
3 上个月
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 = today.year - 1
Order.objects.filter(created_at__year=last_year)
5 单次查询
由于去年+本年包括上月和本月,所有订单>=last_year包括本年,查询非常简单:
Order.objects.filter(created_at__year__gte=last_year)
关于python - 我如何在 django 中查询当年,当月的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28101480/