Django - Delay in creating database entry
<p>I have a Django app where I create a db entry in the view. I then want to perform background processing on the new entry. Instead of sending the created object to the task, I send the object's id then the background task can fetch the db object as explained <a href="http://stackoverflow.com/questions/15079176/should-django-model-object-instances-be-passed-to-celery">here</a>. Below is my code:</p>

<pre><code># In tasks.py
@shared_task
def my_task(model_id):
    my_model = MyModel.objects.get(pk=model_id)
    # Do stuff with my_model

# In views.py:
def some_view(request):
    if request.method == 'POST' and request.is_ajax():
        instance = MyModel.objects.create(**kwargs)
        tasks.my_task.delay(instance.id)
        ....
</code></pre>

<p>However, when I try to get the object in the background task, I get <em>matching query does not exist</em> error. If I add <code>sleep(1)</code> before getting the object, it works as excepted. I do not understand why I'm getting this error, since the object should be in the DB? Does anybody know how to solve this? I don't really want to add a sleep command everywhere.</p>

<p>I'm using Postgres as my DB.</p>

<p>Try this</p>

<pre><code>from django.db import transaction
with transaction.atomic():
    instance = MyModel.objects.create(**kwargs)
tasks.my_task.delay(instance.id)
</code></pre>

python django postgresql