首页 > 解决方案 > Django Filter Queries in List by last x Days with Timedelta 仅显示减去日期的查询,而不是完整范围

问题描述

我正在尝试制作一个列表来显示过去 100 天的查询。如果我在过滤器中使用 Timedelta,我可以列出减去的 Day 的查询。只有确切的日子。但我想列出日期字段中的日期和 Timedelta 过滤器中的日期之间的所有查询。我在做什么错?

class Appointment(models.Model):

    Appointment_Company     = models.ForeignKey(Company,   on_delete=models.CASCADE)
    Appointment_Theme       = models.CharField(max_length=200)
    Appointment_Info        = models.TextField()
    Appointment_Date        = models.DateField(default=datetime.today)


    def __str__(self):
        return self.Appointment_Theme
class AppointmentView(DetailView):


    template_name = 'timecheck/Appointment_100.html'
    model = Company

    def get_context_data(self, *args, **kwargs):

        context = super().get_context_data(**kwargs)
        context['Company_list'] = Company.objects.all()
        context['Appointment_list'] = Appointment.objects.filter(Appointment_Date=datetime.today() - timedelta ( days =  100 ))

        print (context)
        return context

标签: djangodjango-views

解决方案


您需要使用__gte查找 [Django-doc]进行过滤,使其Appointment_Date大于或等于给定值,例如:

context['Appointment_list'] = Appointment.objects.filter(
    Appointment_Date__gte=datetime.today()-timedelta(days=100)
)

推荐阅读