I've a search page that allows users to search for a "ZoningCase" by many different parameters, some from the ZoningCase object and some from several related objects. The user can combine 1 or more of these parameters for their search. My view chains together filters on the queryset based on the parameters selected. All of this works fine. After I've finished chaining filters, I add one additional order_by chain, to sort the cases by case_number. This works, in that the select query django builds is correct, having the correct order by clause at the end.
Next, to prepare the cases for display, I iterate through the queryset and create a custom class for each case, appending that class to a list. Here, it seems, the ordering breaks down. It's as if the iterator ignores the order_by clause and just loops through however it feels like! As I begin the loop, it calls into query.py, the __iter__ method, and looking at self._result_cache, my ZoningCase objects in the queryset are unordered (e.g., 109, 129, 101,...). I can easily fix it by sorting my final list, but since order_by has always worked for me when doing simply queries, I'm wondering if I'm doing something wrong. My relevant code is below. Thanks in advance
for key, value in form.cleaned_data.items():
if key == 'council_district':
if value.count() > 0:
if cases == None:
cases = ZoningCase.objects.filter(councildistrict__in=value)
else:
cases = cases.filter(councildistrict__in=value)
if key == 'cpc':
case_dates = CaseCPCDate.objects.filter(cpc_meeting=value)
if case_dates.count() > 0:
if cases == None:
cases = ZoningCase.objects.filter(casecpcdate__in=case_dates)
else:
cases = cases.filter(casecpcdate__in=case_dates)
if key == 'cc':
case_dates = CaseCCDate.objects.filter(cc_meeting=value)
if case_dates.count() > 0:
if cases == None:
cases = ZoningCase.objects.filter(caseccdate__in=case_dates)
else:
cases = cases.filter(caseccdate__in=case_dates)
if key == 'request_type':
if value.count() > 0:
if cases == None:
cases = ZoningCase.objects.filter(zoningrequest__request_type=value)
else:
cases = cases.filter(zoningrequest__request_type=value)
if value is not None and value != '' and value != False and key != 'cpc' and key != 'cc' and key != 'council_district' and key != 'request_type':
if cases == None:
cases = ZoningCase.objects.filter(**{key: value})
else:
cases = cases.filter(**{key: value})
if cases != None:
cases.order_by('case_number')
for c in cases:
zoningResults.append(ZoningSearchResult(c))