按日期过滤ListView中的对象-Django

问题描述 投票:0回答:2

所以,在我的项目中有一个列表视图,我想在其中显示仅包含当前日期的对象,我正在使用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
python django
2个回答
1
投票
您需要返回过滤的查询集。

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

由于运行.filter(...),它将从filter函数返回一个查询集。您可以将其存储在类似q = queryset.filter(...)的变量中,也可以像上面的示例一样直接将其返回。

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

尝试一下:

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()

© www.soinside.com 2019 - 2024. All rights reserved.