python - 我如何在 django 中查询当年,当月的对象

标签 python django datetime

我需要找到创建的对象总数

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)

问题是

  1. 我想要的 last_month 是日历月而不是 30 天前
  2. 我不确定 created_at__month=this_month 是否匹配当前月份或上一年的同月
  3. 是否可以在单个查询中获取所有计数

最佳答案

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/

相关文章:

python - 序列化具有依赖项的 python 函数

python - scipy.optimize.fmin_bfgs 单个函数同时计算 f 和 fprime

python - Pandas :如何从周和年创建日期时间对象?

python - 在 Python 中镜像日期

c# - 解析从美国时区到日期时间的日期时间。

python - 如何解决 ValueError : Input contains NaN, 无穷大或值对于 dtype ('float64' 来说太大)

python - Sandbox Paypal IPN 不发送响应,适用于实时网站 Paypal

django - 覆盖我的应用程序之外的单个模型的 django 管理更改表单?

django - Django模型中的列排序

django - django bulk_create 查询中的外键关系?