Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - post_save timing issue - how to implement a signal for action "database save finalized"
    primarykey
    data
    text
    <p>it seems to me as if the post_save signal is triggered not when the entire save process has been finalized in the database, but at the end of the model.save() call.</p> <p>I made this observation when executing the following code:</p> <p>models.py</p> <pre><code>class PurchaseOrder(models.Model): total_value = models.DecimalField(max_digits=12, decimal_places=2, null=True, blank=True) def purchase_order_post_save_handler(sender, instance, **kwargs): project_po_value_update_thread = accounting.threads.ProjectPoValueUpdateThread(instance) project_po_value_update_thread.start() post_save.connect(purchase_order_post_save_handler, sender=PurchaseOrder) </code></pre> <p>threads.py</p> <pre><code>class ProjectPoValueUpdateThread(threading.Thread): """ thread to update the po.project with the latest po values called via the save method of the purchase order """ def __init__(self, purchase_order): self.purchase_order = purchase_order threading.Thread.__init__(self) def run(self): "starts the thread to update project po values" try: project = self.purchase_order.project #update active po budget active_po_sum = PurchaseOrder.objects.filter(project=project, is_active=True).aggregate(total_value_sum=Sum('total_value')) active_total_value_sum = active_po_sum['total_value_sum'] project.total_value = active_total_value_sum project.save() </code></pre> <p>In some cases, this code did not update the project total_value correctly, as the instance (which I just saved) queried with PurchaseOrder.objects.filter(project=project, is_active=True) was obviously not updated. Thus it seems to me as the thread has overtaken the instance save method and queried an old version of the model.</p> <p>I know how to overcome this specific problem (just take the latest value from the instance provided by the post_save signal), but I'm wondering how one could create a post_save signal that is triggered when the save action in the database finalized.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload