'objects.get(id = id) only works randomly

I think somewhat related: link. I create a model entry:

def bulk_asset_update(stores, links, img):
    def do_update(id):
        task = ThreadTask.objects.get(pk = id) ## <--- DOES NOT EXIST SOMETIMES

        ...
        task.is_done = True
        task.timestamp_end = timezone.now()
        task.save()

    task = ThreadTask()
    task.name = "update"
    task.save()

    t = threading.Thread(target = do_update, args = [task.id])
    t.setDaemon(True)
    t.start()   
    return {"id": task.id}

Sometimes (every 5th time or so) the ThreadTask.get(pk = id) line fails - so I suspect it might not be written to the database yet maybe? I tried replacing the lines:

task = ThreadTask()
task.name = "update"
task.save()

with:

task = ThreadTask.objects.create(name = "update")

which seams to work better. But can I make sure that the task object is really saved first before code execution continues?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source