简体   繁体   中英

How to filter django queryset for a current week

I am writing this customer admin filter that required to filter the queryset for this/current week only. How can I achieve this

class WeekFilter(admin.SimpleListFilter):
    title = _("Week")
    parameter_name = "week"

    def lookups(self, request, model_admin):
        return (
            ('1', 'This week'),
        )

    def queryset(self, request, queryset):
        if self.value() == '1':
            return queryset.filter() # HERE

I have tried this queryset.filter(created_at__week__gte=1, created-at__week__lte=7) but it doesnt work as expected

I think it might be easier to just fetch the first and last day of this week, and perform a filtering. One can also filter with the __week lookup [Django-doc] on week numbers, but then we will fetch all records for all years with that week number. If we restrict this by a year, then problems might arise if the week is split over two years.

In case we start a week with Monday, we can use:

from datetime import date, timespan

class WeekFilter(admin.SimpleListFilter):
    title = _("Week")
    parameter_name = "week"

    def lookups(self, request, model_admin):
        return (
            ('1', 'This week'),
        )

    def queryset(self, request, queryset):
        if self.value() == '1':
            week_start = date.today()
            week_start -= timedelta(days=week_start.weekday())
            week_end = week_start + timedelta(days=7)
            return queryset.filter(
                created_at__gte=week_start,
                created_at__lt=week_end
            )
        return queryset

For a week that starts on a Sunday, you can replace week_start with:

            week_start -= timedelta(days=)

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