Skip to content

Commit 1ef8667

Browse files
wmuldergovray-oxd
authored andcommitted
DBC22-5405: N+1 fix for coastal ferries
1 parent bd560c3 commit 1ef8667

2 files changed

Lines changed: 39 additions & 5 deletions

File tree

src/backend/apps/ferry/serializers.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,13 @@ class Meta:
104104
)
105105

106106
def get_routes(self, obj):
107-
routes = CoastalFerryRoute.objects.filter(
108-
Q(trips__stop_times__stop=obj) |
109-
Q(trips__stop_times__stop__parent_stop=obj)
110-
).distinct()
107+
if hasattr(obj, 'routes_list'):
108+
routes = obj.routes_list
109+
else:
110+
routes = CoastalFerryRoute.objects.filter(
111+
Q(trips__stop_times__stop=obj) |
112+
Q(trips__stop_times__stop__parent_stop=obj)
113+
).distinct()
111114
return CoastalFerryRouteSerializer(routes, many=True).data
112115

113116
def get_display_category(self, obj):

src/backend/apps/ferry/views.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from apps.ferry.models import CoastalFerryStop, Ferry
1+
from apps.ferry.models import CoastalFerryRoute, CoastalFerryStop, CoastalFerryStopTime, Ferry
22
from apps.ferry.serializers import CoastalFerryStopAPISerializer, FerryRouteSerializer
33
from apps.shared.enums import CacheKey, CacheTimeout
44
from apps.shared.views import CachedListModelMixin
@@ -32,5 +32,36 @@ class CoastalFerryAPI(CachedListModelMixin):
3232
cache_key = CacheKey.COASTAL_FERRY_LIST
3333
cache_timeout = CacheTimeout.COASTAL_FERRY_LIST
3434

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+
3566
class CoastalViewSet(CoastalFerryAPI, viewsets.ReadOnlyModelViewSet):
3667
pass

0 commit comments

Comments
 (0)