[英]Django ORM filter records between last month 15th date to current month 15th date
I want to filter the queryset records from the previous month's 15th date to the current month 15th.我想过滤从上个月的第 15 天到当月的第 15 天的查询集记录。
Does someone have any idea how to do it?有人知道该怎么做吗?
Models.py模型.py
class Book(models.Model):
name = models.CharField(max_length=100, null=True)
author = models.CharField(max_length=100, null=True)
created_on = models.DateTimeField(auto_now_add=True)
Views.py视图.py
class BookView(View):
def get(self, *args, **kwags):
start_date = '15th_of_previous_month'
end_date = '15th_of_current_month'
qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date)
...
You can obtain the 15th of the current month with:您可以通过以下方式获得当月的 15 日:
from django.utils.timezone import now
this_month_15 = now().date().replace(day=15)
Calculating the previous month can be done by subtracting 15 days, and then again replace the day
parameter with 15
:可以通过减去 15 天来计算上个月,然后再次将day
参数替换为15
:
from datetime import timedelta
prev_month_15 = (this_month_15 - timedelta(days=15)).replace(day=15)
This is how I try to solve it:这就是我尝试解决它的方式:
import datetime
today = datetime.date.today()
first = today.replace(day=1) # first date of current month
previous_month_date = first - datetime.timedelta(days=1) # this will be the last day of previous month
start_date = datetime.datetime.strptime(str(previous_month_date.year) + '-' + str(previous_month_date.month) + '-15', '%Y-%m-%d')
end_date = first + datetime.timedelta(days=15)
qs = Book.objects.filter(created_on__gte=start_date,created_on__lt=end_date)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.