Bird
Raised Fist0
Djangoframework~10 mins

Task results and status in Django - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Task results and status
Start Task
Task Running
Task Completes?
NoWait or Retry
Yes
Store Result & Status
Check Status & Result
Display or Use Result
This flow shows how a task starts, runs, completes, stores its result and status, and then how the status and result are checked or displayed.
Execution Sample
Django
from django_q.tasks import async_task

# Start a task
async_task('math.copysign', 1, -1)

# Later check status and result
from django_q.models import Task
result = Task.objects.last().result
status = Task.objects.last().success
This code starts an asynchronous task and later retrieves its result and success status from the database.
Execution Table
StepActionTask StatusResult StoredNotes
1Call async_task to start taskPendingNoneTask is queued to run asynchronously
2Task starts runningRunningNoneTask is executing the function
3Task completes successfullySuccess-1.0Result of math.copysign(1, -1) stored
4Retrieve last task from DBSuccess-1.0Access task status and result
5Use result and statusSuccess-1.0Result -1.0 and success True used in app
6No new tasksN/AN/AExecution stops here
💡 No more tasks to process, final status and result stored
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 4Final
task_statusNonePendingSuccessSuccessSuccess
task_resultNoneNone-1.0-1.0-1.0
Key Moments - 3 Insights
Why is the task status 'Pending' right after calling async_task?
Because the task is only queued to run asynchronously and has not started execution yet, as shown in step 1 of the execution_table.
How do we know the task completed successfully?
At step 3, the status changes to 'Success' and the result is stored, indicating the task finished without errors.
Why do we retrieve the task from the database to get the result?
Because async tasks run outside the main code flow, their results and status are saved in the database for later retrieval, as shown in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the task status immediately after calling async_task?
ARunning
BPending
CSuccess
DFailed
💡 Hint
Check step 1 in the execution_table where the task is just queued.
At which step does the task result get stored?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look for when the result value changes from None to -1.0 in the variable_tracker and execution_table.
If the task failed, what would you expect the 'task_status' to be at step 3?
AFailed
BRunning
CPending
DSuccess
💡 Hint
Refer to the meaning of status values in the execution_table and key_moments.
Concept Snapshot
Task results and status in Django Q:
- async_task() queues a task (status: Pending)
- Task runs asynchronously (status: Running)
- On completion, result and status saved (Success or Failed)
- Retrieve task from DB to check status and result
- Use status to handle success or failure in your app
Full Transcript
In Django Q, when you start a task with async_task, it is first queued with status Pending. Then the task runs asynchronously and its status changes to Running. When the task finishes, the result and status (Success or Failed) are saved in the database. You can later retrieve the task object from the database to check its status and get the result. This lets your app know if the task succeeded and what output it produced.

Practice

(1/5)
1. In Django with Celery, which object do you use to check the status and result of a background task by its ID?
easy
A. AsyncResult
B. TaskStatus
C. TaskResult
D. ResultChecker

Solution

  1. Step 1: Identify the object for task tracking

    Celery provides AsyncResult to track task status and results using the task ID.
  2. Step 2: Confirm usage in Django context

    In Django projects using Celery, AsyncResult is the standard way to check if a task is pending, running, or finished.
  3. Final Answer:

    AsyncResult -> Option A
  4. Quick Check:

    Task status and results = AsyncResult [OK]
Hint: Remember: AsyncResult tracks task status by ID [OK]
Common Mistakes:
  • Confusing AsyncResult with task function names
  • Using non-existent classes like TaskStatus
  • Trying to access results directly without AsyncResult
2. Which of the following is the correct way to create an AsyncResult instance for a task with ID stored in task_id?
easy
A. result = AsyncResult(task=task_id)
B. result = AsyncResult.get(task_id)
C. result = AsyncResult.fetch(task_id)
D. result = AsyncResult(task_id)

Solution

  1. Step 1: Recall AsyncResult constructor usage

    The AsyncResult class is instantiated by passing the task ID as the first argument.
  2. Step 2: Check each option's syntax

    Only AsyncResult(task_id) correctly creates the instance. Methods like .get() or .fetch() are not constructors.
  3. Final Answer:

    result = AsyncResult(task_id) -> Option D
  4. Quick Check:

    Instantiate AsyncResult with task ID directly [OK]
Hint: Use AsyncResult(task_id) to create result object [OK]
Common Mistakes:
  • Calling get() or fetch() as constructor
  • Passing keyword argument 'task' instead of positional
  • Confusing AsyncResult with task function calls
3. Given the code:
result = AsyncResult('abc123')
status = result.status
output = result.result

What will status and output represent if the task is still running?
medium
A. status is 'PENDING', output is None
B. status is 'RUNNING', output is None
C. status is 'FAILURE', output is the error info
D. status is 'SUCCESS', output is the task result

Solution

  1. Step 1: Understand AsyncResult status values

    By default, while a task is running without calling update_state inside the task, result.status remains 'PENDING'.
  2. Step 2: Check result property during running

    result.result returns None until the task completes.
  3. Final Answer:

    status is 'PENDING', output is None -> Option A
  4. Quick Check:

    Running task (default): status='PENDING', result=None [OK]
Hint: Default running tasks show status 'PENDING' and result None [OK]
Common Mistakes:
  • Mistaking for 'RUNNING' status (doesn't exist)
  • Confusing with 'STARTED' which requires explicit update_state
  • Thinking result is available before completion
4. You wrote:
result = AsyncResult(task_id)
if result.status == 'SUCCESS':
    print(result.result)
else:
    print('Task not done')

But it always prints 'Task not done' even after task completion. What is the likely issue?
medium
A. You must call result.get() instead of accessing result.result
B. You should check for 'COMPLETED' instead of 'SUCCESS'
C. The task ID is incorrect or expired
D. AsyncResult does not have a status attribute

Solution

  1. Step 1: Understand status checking logic

    The code checks if result.status equals 'SUCCESS' to print the result.
  2. Step 2: Identify why status never shows 'SUCCESS'

    If the task ID is wrong or expired, AsyncResult will not find the task and status stays 'PENDING' or similar.
  3. Final Answer:

    The task ID is incorrect or expired -> Option C
  4. Quick Check:

    Wrong task ID causes status never to be 'SUCCESS' [OK]
Hint: Check task ID validity if status never changes [OK]
Common Mistakes:
  • Using wrong status string like 'COMPLETED'
  • Assuming result.result always updates without completion
  • Ignoring task ID correctness
5. You want to handle a task result in Django only if it succeeded, otherwise log the error. Which code snippet correctly checks the task status and safely accesses the result or error?
hard
A. result = AsyncResult(task_id) if result.ready(): handle(result.result) else: log_error('Task not ready')
B. result = AsyncResult(task_id) try: handle(result.get(timeout=1)) except Exception as e: log_error(e)
C. result = AsyncResult(task_id) if result.status == 'PENDING': handle(result.result) else: log_error('Task failed')
D. result = AsyncResult(task_id) if result.status == 'SUCCESS': handle(result.result) elif result.status == 'FAILURE': log_error(result.get())

Solution

  1. Step 1: Understand safe result retrieval

    Using result.get() with a timeout waits for completion and raises exceptions on failure.
  2. Step 2: Check error handling approach

    Wrapping result.get() in try-except catches task failures and allows logging errors safely.
  3. Step 3: Compare other options

    Options B, C, and D do not handle exceptions properly; C incorrectly treats 'PENDING' as success.
  4. Final Answer:

    Use try-except with result.get() to handle success and failure -> Option B
  5. Quick Check:

    Use result.get() with try-except for safe task result handling [OK]
Hint: Use try-except with result.get() to catch errors [OK]
Common Mistakes:
  • Checking only status strings without exception handling
  • Assuming ready() means success
  • Treating PENDING as success