소스 검색

Batch migration updates

Jeremy Stretch 2 주 전
부모
커밋
d873876fed
1개의 변경된 파일16개의 추가작업 그리고 3개의 파일을 삭제
  1. 16 3
      netbox/core/migrations/0025_add_job_execution_time.py

+ 16 - 3
netbox/core/migrations/0025_add_job_execution_time.py

@@ -1,15 +1,28 @@
 from django.db import migrations, models
 from django.db import migrations, models
 from django.db.models import DurationField, ExpressionWrapper, F
 from django.db.models import DurationField, ExpressionWrapper, F
 
 
+BATCH_SIZE = 5000
+
 
 
 def populate_execution_time(apps, schema_editor):
 def populate_execution_time(apps, schema_editor):
     """
     """
     Populate execution_time for existing jobs which have both a start and completion time recorded.
     Populate execution_time for existing jobs which have both a start and completion time recorded.
+    Updates are performed in batches, as installations which retain job history indefinitely can
+    accumulate a very large number of rows.
     """
     """
     Job = apps.get_model("core", "Job")
     Job = apps.get_model("core", "Job")
-    Job.objects.filter(started__isnull=False, completed__isnull=False).update(
-        execution_time=ExpressionWrapper(F("completed") - F("started"), output_field=DurationField())
-    )
+    queryset = Job.objects.filter(started__isnull=False, completed__isnull=False)
+    execution_time = ExpressionWrapper(F("completed") - F("started"), output_field=DurationField())
+
+    last_pk = 0
+    while True:
+        pks = list(
+            queryset.filter(pk__gt=last_pk).order_by("pk").values_list("pk", flat=True)[:BATCH_SIZE]
+        )
+        if not pks:
+            break
+        Job.objects.filter(pk__in=pks).update(execution_time=execution_time)
+        last_pk = pks[-1]
 
 
 
 
 class Migration(migrations.Migration):
 class Migration(migrations.Migration):