I have a model (PurchaseOrder - abbreviated PO) holding a time budget. Users can add hour records to this budget, where each hour record reduces the remaining budget.
I implemented signals for updating the remaining budget. After adding an hour record the budget is reduced accordingly. Because the calculation is potentially time consuming I used a thread for this task.
def update_po_remaining_value(sender, instance, **kwargs):
CalculatePOThread(sender, instance).start()
post_save.connect(update_po_remaining_value, sender=HourRecord)
post_delete.connect(update_po_remaining_value, sender=HourRecord)
The thread CalculatePOThread is calculating the remaining PO budget value via getting the hour record set and deducting the total hour record set from the budget
hr_set = HourRecord.objects.filter(purchase_order = po)
At my dev.workspace this works perfectly fine. In production the post_save connect also works fine, but I'm experiencing a strange issue with the post_delete signal. It happens quite often that the sum of hour records returned by the query HourRecord.objects.filter(purchase_order = po) still includes the deleted hour record which has triggered the CalculatePOThread thread.
Anyhow I circumvented the behavior with adding a delay of 6 seconds to the thread before executing the query. time.sleep(6).
Does anybody has an idea why this situation can occur? it seems like the post_delete signal is triggered before the record is really deleted from the database..!? But this would be a bug in Django and this would be my last guess.