@andrewgodwin Django already raises SynchronousOnlyOperation
where querying from an async context. Instead of raising, could it return a proxy object with __await__
declared (or just an async def
coroutine wrapper function), providing async capabilities?
This could be set up as a decorator for things like .get()
and .save()
, and could initially just return a sync_to_async(func)
version of the method, but could also look for an async variant of the method (renamed appropriately, e.g. _async_methodname
) on the object.
Another option is to use the inspect framework to walk the stack and see if we’re in a coroutine (instead of looking for the running event loop), but I’m not sure how efficient that is (or if you can even identify coroutines within inspect, but I’d expect you can). Not sure if this is worth doing, but I felt it might be worth listing.
This should allow full compatibility with the existing api, and could even potentially work for properties that weren’t collected with select_related
.