Reputation: 35
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
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
I know this data isn't filtered because the entire customer list is 521 entries of mock data that are active. I was following information from this question: 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?
Upvotes: 1
Views: 196
Reputation: 126
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
Upvotes: 1