title: handle `post_save` signal in celery
body: <p>I have a rather long running task that needs to be executed after inserting or updating an specific model.</p>
  
  <p>I decided to use <code>post_save</code> signal instead of overriding <code>save</code> method to reduce coupling. Since Django signals are not asynchronous I had to do the long running job as a Celery task (which we already have in our stack).</p>
  
  <p>A simplified version of my signal handling function is as follows:</p>
  
  <pre><code>@receiver(post_save, sender=MyModel)
  def my_model_post_save(sender, instance, **kwargs):
      handle_save_task.apply_async(args=(instance.pk,))
  </code></pre>
  
  <p>Also, because the job is done asynchronously I passed the primary key of the object instead of the instance itself.</p>
  
  <pre><code>@app.task(queue='elastic')
  def handle_save_task(instance_pk):
      try:
          instance = MyModel.objects.get(pk=instance_pk)
      except ObjectDoesNotExist:
          # Abort
          logger.warning("Saved object was deleted before this task get a chance to be executed [id = %d]" % instance_pk)
      else:
          # Do my things with instance
  </code></pre>
  
  <p>The actual problem is that when the celery task is executed it can't access the newly saved instance. Just like if it was executed prior to saving! (wasn't the signal called <strong>post_</strong>save? What an irony)</p>
  
  <p>By "executed before saving" I mean if it is a new instance that's being inserted to DB, in the celery task I get an <code>DoesNotExist</code> exception and in cases where instance was already in DB and the save method was called to update some of its properties I get the old instance with old property values in the celery task.</p>
  
  <p>A workaround is to run celery tasks with a few seconds of delay, but obviously it is not a good solution and also can not guarantee the proper execution behavior under heavy loads or long network delays.</p>
  
  <p>Am I doing it completely wrong or with some slight modifications I can make it work? </p>