Bird
0
0

You want to run a blocking database query inside an async Django view without blocking the event loop. Which approach is correct?

hard📝 Application Q9 of 15
Django - Async Django
You want to run a blocking database query inside an async Django view without blocking the event loop. Which approach is correct?
ACall the database query directly inside the async view without changes.
BUse <code>sync_to_async</code> decorator or function to run the query asynchronously.
CConvert the database query to an async function manually.
DRun the query in a separate thread without any Django utilities.
Step-by-Step Solution
Solution:
  1. Step 1: Understand blocking calls in async views

    Database queries are usually blocking; to avoid blocking the event loop, use Django's sync_to_async utility.
  2. Step 2: Evaluate options

    Use sync_to_async decorator or function to run the query asynchronously. correctly uses sync_to_async. Call the database query directly inside the async view without changes. blocks event loop. Convert the database query to an async function manually. is not feasible as Django ORM is sync. Run the query in a separate thread without any Django utilities. is risky without Django's helpers.
  3. Final Answer:

    Use sync_to_async decorator or function to run the query asynchronously. -> Option B
  4. Quick Check:

    Use sync_to_async for blocking DB calls in async views [OK]
Quick Trick: Wrap blocking DB calls with sync_to_async in async views [OK]
Common Mistakes:
MISTAKES
  • Calling DB queries directly in async views
  • Trying to make ORM async manually
  • Ignoring event loop blocking

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Django Quizzes