Skip to content

Commit 57777c2

Browse files
committed
Handle IntegrityError in bulk_update fallback logic
Wraps the fleet.objects.bulk_update call in a try/except block to catch IntegrityError exceptions. If a bulk update fails due to integrity issues, the code now falls back to updating vehicles individually, skipping those that still raise errors, and logs the process for better traceability.
1 parent 49cd094 commit 57777c2

1 file changed

Lines changed: 20 additions & 6 deletions

File tree

tracking/management/commands/simulate_positions.py

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from datetime import timedelta
66
from tracking.models import Trip
77
from fleet.models import fleet
8+
from django.db import IntegrityError
89
from routes.models import routeStop
910
import time
1011

@@ -196,12 +197,25 @@ def handle(self, *args, **kwargs):
196197
# ---------------------------------------------------------
197198
if vehicles_to_update:
198199
t3 = time.time()
199-
fleet.objects.bulk_update(
200-
vehicles_to_update,
201-
["sim_lat", "sim_lon", "sim_heading", "current_trip", "updated_at"],
202-
batch_size=500
203-
)
204-
self.stdout.write(f"Updated {len(vehicles_to_update)} vehicles in {time.time() - t3:.2f}s")
200+
try:
201+
fleet.objects.bulk_update(
202+
vehicles_to_update,
203+
["sim_lat", "sim_lon", "sim_heading", "current_trip", "updated_at"],
204+
batch_size=500
205+
)
206+
self.stdout.write(f"Updated {len(vehicles_to_update)} vehicles in {time.time() - t3:.2f}s")
207+
except IntegrityError as e:
208+
# Bulk update failed due to FK integrity (race or missing trip). Fall back
209+
# to per-vehicle save so we can skip problematic updates.
210+
self.stderr.write(f"Bulk update IntegrityError: {e}. Falling back to per-vehicle updates.")
211+
updated = 0
212+
for v in vehicles_to_update:
213+
try:
214+
v.save(update_fields=["sim_lat", "sim_lon", "sim_heading", "current_trip", "updated_at"])
215+
updated += 1
216+
except IntegrityError as e2:
217+
self.stderr.write(f"Skipping vehicle {v.id} due to IntegrityError: {e2}")
218+
self.stdout.write(f"Fallback updated {updated} vehicles in {time.time() - t3:.2f}s")
205219

206220
self.stdout.write(f"Total time: {time.time() - t0:.2f}s")
207221

0 commit comments

Comments
 (0)