简体   繁体   中英

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.

Does someone have any idea how to do it?

Models.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

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:

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 :

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM