1414from django .core import serializers
1515from django .core .exceptions import PermissionDenied , ValidationError
1616from django .db import models
17- from django .db .models import F , QuerySet
17+ from django .db .models import F , QuerySet , Value
1818from django .db .models .functions import Coalesce , ExtractDay , Length , TruncDate
1919from django .db .models .query import Prefetch
2020from django .http import Http404 , HttpRequest , HttpResponse , HttpResponseRedirect , JsonResponse , StreamingHttpResponse
@@ -256,6 +256,11 @@ def filter_findings_by_filter_name(self, findings: QuerySet[Finding]):
256256 return findings
257257
258258 def filter_findings_by_form (self , request : HttpRequest , findings : QuerySet [Finding ]):
259+ # Apply default ordering if no ordering parameter is provided
260+ # This maintains backward compatibility with the previous behavior
261+ if not request .GET .get ("o" ):
262+ findings = findings .order_by (self .get_order_by ())
263+
259264 # Set up the args for the form
260265 args = [request .GET , findings ]
261266 # Set the initial form args
@@ -276,11 +281,19 @@ def filter_findings_by_form(self, request: HttpRequest, findings: QuerySet[Findi
276281 def get_filtered_findings (self ):
277282 findings = get_authorized_findings (Permissions .Finding_View )
278283 # Annotate computed SLA age in days: sla_expiration_date - (sla_start_date or date)
284+ # Handle NULL sla_expiration_date by using Coalesce to provide a large default value
285+ # so NULLs sort last when sorting ascending (most urgent first)
279286 findings = findings .annotate (
280- sla_age_days = ExtractDay (
281- F ("sla_expiration_date" ) - Coalesce (F ("sla_start_date" ), TruncDate ("created" )),
287+ sla_age_days = Coalesce (
288+ ExtractDay (
289+ F ("sla_expiration_date" ) - Coalesce (F ("sla_start_date" ), TruncDate ("created" )),
290+ ),
291+ Value (999999 ), # Large value to push NULLs to the end when sorting ascending
292+ output_field = models .IntegerField (),
282293 ),
283- ).order_by (self .get_order_by ())
294+ )
295+ # Don't apply initial order_by here - let OrderingFilter handle it via request.GET['o']
296+ # This prevents conflicts between initial ordering and user-requested sorting
284297 findings = self .filter_findings_by_object (findings )
285298 return self .filter_findings_by_filter_name (findings )
286299
0 commit comments