如何在江中查询本年、本月对象

2024-05-23 04:05:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要找到在中创建的所有对象

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

使用like

Order.objects.filter(created_at__month=this_month)

问题是

  1. 我要的最后一个月是日历月,不是30天以前
  2. 我不确定创建的月份是否与当前月份或上一年的同一月份相匹配
  3. 是否可以在一个查询中获取所有计数

Tags: 对象todaydatetimeobjectsordercurrentthisdays
3条回答

如果您希望在单独的查询中使用它,请执行类似的操作。

from_this_year = Order.objects.filter(created_at__year=this_year)
from_last_year = Order.objects.filter(created_at__year=last_year)
from_june = Order.objects.filter(created_at__month='06',created_at__year=this_year)
from_this_month = Order.objects.filter(created_at__month=this_month,created_at__year=this.year)

注意:在我的例子中,我把'06'放在六月,但是你可以改变它。

我不认为你可以只匹配日期字段的“月”或“年”部分,而不做一些重要的修改或注释。最有可能的是,您最简单的解决方案是定义所需范围的开始和结束,并根据该范围进行搜索。这可能需要一点工作。

例如,上个日历月是:

today = datetime.now()
if today.month == 1:
    last_month_start = datetime.date(today.year-1, 12, 1)
    last_month_end = datetime.date(today.year-1, 12, 31)
else:
    last_month_start = datetime.date(today.year, today.month -1, 1)
    last_month_end = datetime.date(today.year, today.month, 1) - datetime.timedelta(days=1)
Order.objects.filter(created_at__gte=last_month_start, created_at__lte=last_month_end)

GTE和LTE是“大于或等于”和“小于或等于”。同样值得注意的是,我们使用timedelta来计算本月1日的前一天是什么,而不是查看前一个月是28天、29天、30天还是31天的所有不同情况。

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单一查询

由于去年+本年包括上月和本月,并且所有订单都包含上一年,因此查询非常简单:

Order.objects.filter(created_at__year__gte=last_year)

相关问题 更多 >

    热门问题