擅长:python、mysql、java
<p>我不认为你可以只匹配日期字段的“月”或“年”部分,而不做一些重要的修改或注释。最有可能的是,您最简单的解决方案是定义所需范围的开始和结束,并根据该范围进行搜索。这可能需要一点工作。</p>
<p>例如,上个日历月是:</p>
<pre><code>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)
</code></pre>
<p>GTE和LTE是“大于或等于”和“小于或等于”。同样值得注意的是,我们使用timedelta来计算本月1日的前一天是什么,而不是查看前一个月是28天、29天、30天还是31天的所有不同情况。</p>