2
2
import logging
3
3
4
4
from django .core .management .base import BaseCommand
5
+ from django .db .models import Prefetch , Q
5
6
6
7
from telemetry .influx import Influx
7
8
from telemetry .models import FastLap , Lap , Session
@@ -71,6 +72,12 @@ def add_arguments(self, parser):
71
72
action = "store_true" ,
72
73
)
73
74
75
+ parser .add_argument (
76
+ "--fix-session-car-track" ,
77
+ help = "fix sessions missing car or track by using data from first lap" ,
78
+ action = "store_true" ,
79
+ )
80
+
74
81
def handle (self , * args , ** options ):
75
82
if options ["delete_influx" ]:
76
83
self .influx = Influx ()
@@ -87,6 +94,8 @@ def handle(self, *args, **options):
87
94
self .dump_session ()
88
95
elif options ["fix_cars" ]:
89
96
self .fix_cars ()
97
+ elif options ["fix_session_car_track" ]:
98
+ self .fix_session_car_track ()
90
99
91
100
def fix_cars (self ):
92
101
from django .db .models import Count
@@ -133,6 +142,38 @@ def fix_cars(self):
133
142
# else:
134
143
# print("\nNo cars without associated sessions found.")
135
144
145
+ def fix_session_car_track (self ):
146
+ """
147
+ Find sessions missing car or track and set them from the first lap's data.
148
+ Process in batches to handle large numbers of sessions efficiently.
149
+ """
150
+
151
+ batch_size = 1000
152
+ sessions = Session .objects .filter (Q (car__isnull = True ) | Q (track__isnull = True )).prefetch_related (Prefetch ("laps" , queryset = Lap .objects .order_by ("number" )))
153
+
154
+ total = sessions .count ()
155
+ print (f"Found { total } sessions with missing car or track" )
156
+
157
+ processed = 0
158
+ for session in sessions .iterator (chunk_size = batch_size ):
159
+ first_lap = session .laps .first ()
160
+ if first_lap :
161
+ updated = False
162
+ if not session .car and first_lap .car :
163
+ session .car = first_lap .car
164
+ updated = True
165
+ if not session .track and first_lap .track :
166
+ session .track = first_lap .track
167
+ updated = True
168
+
169
+ if updated :
170
+ session .save ()
171
+ processed += 1
172
+ if processed % 100 == 0 :
173
+ print (f"Processed { processed } /{ total } sessions" )
174
+
175
+ print (f"Updated { processed } sessions with car/track data from their laps" )
176
+
136
177
def dump_session (self ):
137
178
# TODO: Revisit this method. The Telemetry model is not defined.
138
179
# Uncomment and fix the code below once the Telemetry model is available.
0 commit comments