Context manager to pick which database to use?

81 views
Skip to first unread message

Peter Coles

unread,
Apr 28, 2015, 3:26:48 PM4/28/15
to django...@googlegroups.com
When using multiple databases, I would love for a simple way to declare which database should be used during execution of django ORM calls. Perhaps this could even use a context manager and look something like this:

# declare that all calls within this context should default to using 'readonly' db instead of 'default'
with database('readonly'):
    things
= models.MyThing.objects.all()


   
# inside this function call the 'readonly' db would be used too (unless overridden by `.using(...)`)
    more_things
= some_lib.some_function(things)

In my app I have a write database and a read-only replica. The read-only replica might have a delay, so I don’t want to use it in normal live requests, but I would like certain dashboards to use it. For this reason I assume that the database router approach doesn't properly apply?

Does something like this exist? If not, any thoughts on if it might be useful and where I might consider poking around in the ORM?

Peter Coles

unread,
Apr 28, 2015, 3:35:16 PM4/28/15
to django...@googlegroups.com
Or maybe more versatile would be a context manager that accepts a database router. Something like the following?

with database_router(my_router):
   

Simon Charette

unread,
Apr 28, 2015, 3:58:15 PM4/28/15
to django...@googlegroups.com
Hi Peter,

I think you could use database routers to declare the default behavior and rely on the using() queryset method for the exceptional case?

I'm afraid the introduction of a context manager would require the addition of a thread-local global state that a database router could rely on.

Simon

Peter Coles

unread,
Apr 28, 2015, 4:54:25 PM4/28/15
to django...@googlegroups.com
Thanks for the reply Simon. Yeah, I’m using `using` for now, just thought it’d be nice to somehow wrap the logic, especially if it could magically pass through to underlying function calls. I am experimenting with having a `readonly` manager that just adds a `.using('readonly')`, dunno how ~djangonic~ that is.

Cheers,
Peter
Reply all
Reply to author
Forward
0 new messages