|
3 | 3 | from django.shortcuts import redirect, get_object_or_404 |
4 | 4 | from django.urls import reverse |
5 | 5 | from django.views.generic import ListView, DetailView, CreateView |
6 | | -from django.db.models import Q, Max |
| 6 | +from django.db.models import Q, Max, OuterRef, Subquery |
7 | 7 | from django.http import JsonResponse |
8 | 8 | from django_drf_filepond.api import store_upload |
9 | 9 | from django_drf_filepond.models import TemporaryUpload |
@@ -142,7 +142,22 @@ def get_queryset(self): |
142 | 142 | # Filter non-empty values |
143 | 143 | statuses = [stat for stat in statuses if stat.strip()] |
144 | 144 | if statuses: |
145 | | - queryset = queryset.filter(local_status__in=statuses) |
| 145 | + # Annotate each asset with its latest status from StatusChanges |
| 146 | + latest_status = StatusChange.objects.filter( |
| 147 | + asset=OuterRef('pk'), |
| 148 | + new_status__isnull=False |
| 149 | + ).order_by('-status_date', '-created_at').values('new_status')[:1] |
| 150 | + |
| 151 | + queryset = queryset.annotate( |
| 152 | + latest_status_from_changes=Subquery(latest_status) |
| 153 | + ) |
| 154 | + |
| 155 | + # Filter where either the latest status change matches OR |
| 156 | + # no status changes exist and local_status matches |
| 157 | + queryset = queryset.filter( |
| 158 | + Q(latest_status_from_changes__in=statuses) | |
| 159 | + Q(latest_status_from_changes__isnull=True, local_status__in=statuses) |
| 160 | + ) |
146 | 161 |
|
147 | 162 | if locations: |
148 | 163 | # Filter non-empty values |
|
0 commit comments