我正在编写此客户管理过滤器,该过滤器仅需要对此/当前周的查询集进行过滤。我该如何实现
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
我尝试过this queryset.filter(created_at__week__gte = 1,created-at__week__lte = 7),但它没有按预期工作
答案 0 :(得分:1)
我认为仅获取本周的第一天和最后一天并执行过滤可能会更容易。您还可以使用__week
lookup [Django-doc]来筛选星期编号,但是我们将使用该星期编号来提取 all 年的所有记录。如果我们将其限制为一年,那么如果将一周分为两年,则可能会出现问题。
如果我们从星期一开始一周,我们可以使用:
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
对于从星期日开始的一周,您可以将week_start
替换为:
week_start -= timedelta(days=(week_start.weekday()-1)%7)