简体   繁体   English

Django Class 基于视图过滤查询集但不是?

[英]Django Class based view filtering queryset but not?

I have a bit of a challenge with the way a date filter is working:我对日期过滤器的工作方式有点挑战:

Django Class based view, starting here https://github.com/varlenthegray/wcadmin/blob/master/customer/views.py#L61基于 Django Class 的视图,从这里开始https://github.com/varlenthegray/wcadmin/blob/master/customer/views.py#L61

class CustomersCustomReport(generic.ListView):
    model = Customer
    template_name = 'customer/reports/custom_report.html'

    def get_queryset(self):
        from_date = self.request.GET.get('fromDate')
        to_date = self.request.GET.get('toDate')
        self.queryset = Customer.objects.filter(is_active=True)

        if from_date:
            from_date = datetime.strptime(from_date, '%m-%d-%Y').strftime('%Y-%m-%d')
            print("Checking date from " + from_date)

            self.queryset.filter(next_service__gte=from_date)

        if to_date:
            to_date = datetime.strptime(to_date, '%m-%d-%Y').strftime('%Y-%m-%d')
            print("Checking date to " + to_date)
            self.queryset.filter(next_service__lte=to_date)

        return self.queryset

I'm expecting this to return a filtered query based on the date that is a form field.我希望这会根据作为表单字段的日期返回经过过滤的查询。

https://wcadmin.innovated.tech/customer/report/custom_report?fromDate=04-01-2022&toDate=04-30-2022 https://wcadmin.innovated.tech/customer/report/custom_report?fromDate=04-01-2022&toDate=04-30-2022

I know this data isn't filtered because the entire customer list is 521 entries of mock data that are active.我知道此数据未被过滤,因为整个客户列表包含 521 个活动的模拟数据条目。 I was following information from this question: How Can I Filter By Date Range Using Djangos Built in ListView?我正在关注这个问题的信息: How Can I Filter By Date Range Using Djangos Built in ListView?

I know it's getting data from the database, I know it's getting the date range I want from the URL due to the print, and the model is set to DateField for next_service, so I'm not quite sure what's going wrong here?我知道它从数据库获取数据,我知道它从 URL 获取我想要的日期范围,因为打印,model 被设置为 next_service 的 DateField,所以我不太确定这里出了什么问题?

you need only a little changes:你只需要一点点改变:

def get_queryset(self):
    from_date = self.request.GET.get('fromDate')
    to_date = self.request.GET.get('toDate')
    queryset = Customer.objects.filter(is_active=True) # change

    if from_date:
        from_date = datetime.strptime(from_date, '%m-%d-%Y').strftime('%Y-%m-%d')
        print("Checking date from " + from_date)

        queryset = queryset.filter(next_service__gte=from_date) # change

    if to_date:
        to_date = datetime.strptime(to_date, '%m-%d-%Y').strftime('%Y-%m-%d')
        print("Checking date to " + to_date)
        queryset = queryset.filter(next_service__lte=to_date) # change

    return queryset # change

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM