在我的Django应用程序中,在管理员中,对于我的某个模型,我允许该选项按其' create_date'进行过滤。领域。 Django默认给了我一些选项(今天,过去7天,本月,今年)。我想简单地添加选项以选择'昨天'同样。我查看了有关同一问题的其他Stack溢出问题,但他们都在寻找按日期范围搜索的能力,而我只想要一个预加载的选项。他们是在管理类中配置此模型以覆盖其某些过滤器功能的方法吗?
管理员班级
class User_LikeAdmin(admin.ModelAdmin):
def fb_view_link(self, obj):
if len(obj.user_facebook_link) > 2:
return u"<a href='%s' target='_blank'>Facebook Page</a>" % obj.user_facebook_link
else:
return ""
fb_view_link.short_description = ''
fb_view_link.allow_tags = True
list_display = ('vehicle', 'user', 'fb_view_link', 'dealer', 'create_date')
list_filter = ('create_date', ('vehicle__dealer', custom_titled_filter('Dealer')))
raw_id_fields = ('vehicle', 'user')
actions = [export_csv]
def dealer(self, obj):
return obj.vehicle.dealer
答案 0 :(得分:3)
作为选项,您可以使用documentation
中提到的自定义过滤器类class User_LikeAdmin(admin.ModelAdmin):
list_filter = (('create_date', CustomDateFieldListFilter),)
您可以延长DateFieldListFilter
from django.contrib.admin.filters import DateFieldListFilter
class CustomDateFieldListFilter(DateFieldListFilter):
# Your tweaks here
答案 1 :(得分:1)
使用 datetime ,创建昨天变量,然后以这种方式获取所有记录。
import datetime
yesterday = datetime.date.today() - datetime.timedelta(days=1)
data = Modelname.objects.filter(create_date=yesterday)
答案 2 :(得分:1)
import datetime
from django.contrib.admin import DateFieldListFilter
class DateYesterdayFieldListFilter(DateFieldListFilter):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
self.links = list(self.links)
self.links.insert(2, ('Yesterday', {
self.lookup_kwarg_since: str(yesterday),
self.lookup_kwarg_until: str(today),
}))
答案 3 :(得分:0)
我的@ d2718nis版本:
class DateFilter(DateFieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
super().__init__(field, request, params, model, model_admin, field_path)
now = timezone.now()
if timezone.is_aware(now):
now = timezone.localtime(now)
if isinstance(field, models.DateTimeField):
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
else: # field is a models.DateField
today = now.date()
yesterday = today - datetime.timedelta(days=1)
links_start = self.links[:2] # anyday and today
link_yesterday = (_('Yesterday'), {
self.lookup_kwarg_since: str(yesterday),
self.lookup_kwarg_until: str(today),
})
self.links = (*links_start, link_yesterday, *self.links[2:])