From e575c5649dcb431167567fcacd179eb257be6891 Mon Sep 17 00:00:00 2001 From: casper moyo Date: Tue, 31 Mar 2026 16:23:03 +0200 Subject: [PATCH] Fix: upsert fiscal counter race condition with F, db row locking --- fiscguy/zimra_receipt_handler.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/fiscguy/zimra_receipt_handler.py b/fiscguy/zimra_receipt_handler.py index 5a0285c..a4efe2b 100644 --- a/fiscguy/zimra_receipt_handler.py +++ b/fiscguy/zimra_receipt_handler.py @@ -13,6 +13,7 @@ import qrcode from django.core.files.base import ContentFile from django.db import DatabaseError +from django.db.models import F from loguru import logger from fiscguy.exceptions import ReceiptSubmissionError @@ -507,8 +508,9 @@ def _upsert_counter( defaults={"fiscal_counter_value": amount}, ) if not created: - counter.fiscal_counter_value += amount - counter.save() + FiscalCounter.objects.filter(pk=counter.pk).update( + fiscal_counter_value=F("fiscal_counter_value") + amount + ) except DatabaseError as exc: logger.exception(f"Failed to upsert {counter_type} counter for device {self._device}") raise ReceiptSubmissionError(f"Failed to update {counter_type} fiscal counter") from exc