简体   繁体   English

Django ORM过滤上个月15日到本月15日之间的记录

[英]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.

相关问题 select 按日期记录,其中日期是该月上一个工作日的 15 日 - select records by date, where date is 15th ot the previous business day of the month 需要计算从下个月15号到15号的操作总和 - Need to count the total sum of operations from 15th day to 15th day of next month 确定在第15天之后会转到下个月的当前月份变量-python 2.7 - Determine current month variable that rolls over to next month after the 15th day- python 2.7 计算python中每月的第1个或第15个月的时间 - Calculating time until 1st or 15th of the month in python Discord.py 每月15号发一个embed - Discord.py Sending an embed on the 15th every month 如何线性插补从下个月15日开始的每月15号的每月数据 - how to linearly interpolate monthly data from the 15th of each month that rolls over the 15th of the next month Select 每月的第一天/第十五天加上 python 的前后一天 - Select first/15th day of month plus the day before and after in python pandas 每月重新抽样第 15 天 - pandas monthly resample 15th day 使用正则表达式匹配长 integer 中的第 10 位到第 15 位数字并替换为 * - Using regex to match 10th to 15th digits in a long integer and replace with * 当产生 15 个球时,第 15 次点击后游戏停止反应 - Game stops reacting after 15th click when 15 balls generated
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM