按日期Django筛选ListView中的对象

2024-09-29 21:46:45 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,在我的项目中,有一个listview,我想在其中显示仅包含当前日期的对象,我使用datetime模块并覆盖getquery方法,但是该视图显示了所有元素,无论日期是什么

看法

date = datetime.date.today()

class AppointmentIndexView(ListView):
    model = Consults
    template_name = 'appointments_index.html'
    context_object_name = 'consults'
    paginate_by = 7

    def get_queryset(self):
        queryset  = super().get_queryset()
        queryset.filter(Fecha=date)
        return queryset

Tags: 模块项目对象方法name视图元素get
2条回答

据我所知,您的问题是queryset.filter()不会更新原始查询集。因此,当您返回queryset时,实际上是返回原始版本,而不是经过过滤的版本

试试这个:

date = datetime.date.today()

class AppointmentIndexView(ListView):
    model = Consults
    template_name = 'appointments_index.html'
    context_object_name = 'consults'
    paginate_by = 7

    def get_queryset(self):
        return super().get_queryset().filter(Fecha=date)

此外,在Django中,您应该使用时区感知的日期/时间

from django.utils import timezone
date = timezone.localdate()

您需要返回过滤后的查询集

class AppointmentIndexView(ListView):
    ...
    def get_queryset(self):
        queryset  = super().get_queryset()
        return queryset.filter(Fecha=date)

因为当您运行.filter(...)时,它将从filter函数返回一个queryset。您可以将其存储在q = queryset.filter(...)之类的变量中,也可以像上面的示例那样直接返回它

相关问题 更多 >

    热门问题