[英]select records by date, where date is 15th ot the previous business day of the month
[英]Django ORM filter records between last month 15th date to current month 15th date
我想过滤从上个月的第 15 天到当月的第 15 天的查询集记录。
有人知道该怎么做吗?
模型.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)
视图.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)
...
您可以通过以下方式获得当月的 15 日:
from django.utils.timezone import now
this_month_15 = now().date().replace(day=15)
可以通过减去 15 天来计算上个月,然后再次将day
参数替换为15
:
from datetime import timedelta
prev_month_15 = (this_month_15 - timedelta(days=15)).replace(day=15)
这就是我尝试解决它的方式:
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.