|
1 | | -from apps.ferry.models import CoastalFerryStop, Ferry |
| 1 | +from apps.ferry.models import CoastalFerryRoute, CoastalFerryStop, CoastalFerryStopTime, Ferry |
2 | 2 | from apps.ferry.serializers import CoastalFerryStopAPISerializer, FerryRouteSerializer |
3 | 3 | from apps.shared.enums import CacheKey, CacheTimeout |
4 | 4 | from apps.shared.views import CachedListModelMixin |
@@ -32,5 +32,36 @@ class CoastalFerryAPI(CachedListModelMixin): |
32 | 32 | cache_key = CacheKey.COASTAL_FERRY_LIST |
33 | 33 | cache_timeout = CacheTimeout.COASTAL_FERRY_LIST |
34 | 34 |
|
| 35 | + def fetch_list_data(self, queryset=None): |
| 36 | + stops = list(CoastalFerryStop.objects.filter(parent_stop=None)) |
| 37 | + stop_map = {s.id: s for s in stops} |
| 38 | + |
| 39 | + for s in stops: |
| 40 | + s.routes_list = set() |
| 41 | + |
| 42 | + associations = CoastalFerryStopTime.objects.values_list( |
| 43 | + 'trip__route_id', |
| 44 | + 'stop_id', |
| 45 | + 'stop__parent_stop_id' |
| 46 | + ).order_by().distinct() |
| 47 | + |
| 48 | + all_routes = {r.id: r for r in CoastalFerryRoute.objects.all()} |
| 49 | + |
| 50 | + for route_id, stop_id, parent_stop_id in associations: |
| 51 | + route = all_routes.get(route_id) |
| 52 | + if not route: |
| 53 | + continue |
| 54 | + |
| 55 | + if stop_id in stop_map: |
| 56 | + stop_map[stop_id].routes_list.add(route) |
| 57 | + |
| 58 | + if parent_stop_id and parent_stop_id in stop_map: |
| 59 | + stop_map[parent_stop_id].routes_list.add(route) |
| 60 | + |
| 61 | + for s in stops: |
| 62 | + s.routes_list = sorted(list(s.routes_list), key=lambda r: r.id) |
| 63 | + |
| 64 | + return self.get_serializer(stops, many=True).data |
| 65 | + |
35 | 66 | class CoastalViewSet(CoastalFerryAPI, viewsets.ReadOnlyModelViewSet): |
36 | 67 | pass |
0 commit comments