From 8fb0f9ec418516dbcfb35302e18e2df560ff1913 Mon Sep 17 00:00:00 2001 From: rostyslavhereha Date: Tue, 31 Oct 2023 19:14:37 +0200 Subject: [PATCH] optimize post_save() signal. --- label_studio/tasks/api.py | 14 ++++++++------ label_studio/tasks/models.py | 5 +++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/label_studio/tasks/api.py b/label_studio/tasks/api.py index b6b5c1fcaac1..cb43e3eb3f21 100644 --- a/label_studio/tasks/api.py +++ b/label_studio/tasks/api.py @@ -559,14 +559,16 @@ def create(self, request, *args, **kwargs): predictions_array = request_data.get("result", []) tasks_array = request_data.get("task", []) predictions_to_create = [] + tasks = Task.objects.select_related('project').in_bulk(tasks_array) + data = request_data.copy() for prediction, task_id in zip(predictions_array, tasks_array): - data = request_data.copy() data["result"] = prediction - data["task"] = Task.objects.get(id=task_id) - predictions_to_create.append(Prediction(**data)) - predictions = Prediction.objects.bulk_create(predictions_to_create) - for prediction in predictions: - post_save.send(sender=Prediction, instance=prediction, creared=True) + data["task"] = tasks.get(task_id) + pred = Prediction(**data) + predictions_to_create.append(pred) + post_save.send(sender=Prediction, instance=pred, creared=True) + + Prediction.objects.bulk_create(predictions_to_create) return Response(data={'success': 'Predictions created successfully.'}, status=status.HTTP_201_CREATED) @method_decorator(name='get', decorator=swagger_auto_schema(auto_schema=None)) diff --git a/label_studio/tasks/models.py b/label_studio/tasks/models.py index 9c3ad44dc333..0700582962a7 100644 --- a/label_studio/tasks/models.py +++ b/label_studio/tasks/models.py @@ -877,8 +877,9 @@ def remove_predictions_from_project(sender, instance, **kwargs): @receiver(post_save, sender=Prediction) def save_predictions_to_project(sender, instance, **kwargs): """Add predictions counters""" - instance.task.total_predictions = instance.task.predictions.all().count() - instance.task.save(update_fields=['total_predictions']) + task_id = instance.task_id + predictions_count = Prediction.objects.filter(task_id=task_id).count() + Task.objects.filter(id=task_id).update(total_predictions=predictions_count + 1) logger.debug(f"Updated total_predictions for {instance.task.id}.") # =========== END OF PROJECT SUMMARY UPDATES ===========