Skip to content
Latchkey

Django Channels "SynchronousOnlyOperation" async DB access in CI

Django blocks synchronous ORM calls from an async context to prevent blocking the event loop. In a Channels consumer test, calling the ORM directly inside an async function raises SynchronousOnlyOperation unless the call is wrapped for async use.

What this error means

An async consumer test fails with "django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async."

Django
django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an
async context - use a thread or sync_to_async.

Common causes

A synchronous ORM call inside async code

A consumer or async test function calls Model.objects.get(...) directly, which is synchronous and forbidden in the event loop.

Missing async test database configuration

The async test does not use the async-safe ORM APIs or a sync_to_async wrapper, so any DB touch trips the guard.

How to fix it

Wrap sync ORM calls for async

Use sync_to_async (or the async ORM methods) so the DB call runs safely off the event loop.

app/consumers.py
from asgiref.sync import sync_to_async

async def get_thing(pk):
    return await sync_to_async(Thing.objects.get)(pk=pk)

Use async ORM methods where available

Recent Django exposes async query methods that avoid the wrapper.

app/consumers.py
thing = await Thing.objects.aget(pk=pk)

How to prevent it

  • Never call the synchronous ORM directly inside async code.
  • Wrap unavoidable sync calls with sync_to_async.
  • Prefer Django async ORM methods in Channels consumers.

Frequently asked questions

What causes ""You cannot call this from an async context""?
A consumer or async test function calls Model.objects.get(...) directly, which is synchronous and forbidden in the event loop.
How do I fix "You cannot call this from an async context"?
Use sync_to_async (or the async ORM methods) so the DB call runs safely off the event loop.

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card