Feature Idea for overwrite_default_connection context manager

59 views
Skip to first unread message

Alexander Lyabah

unread,
Jun 1, 2022, 9:21:02 AM6/1/22
to Django developers (Contributions to Django itself)
In some of the previous version on Django I had a very useful context manager.

from contextlib import ContextDecorator
from django.db import connections

class overwrite_default_connection(ContextDecorator):
    prev_default = None
    write_connection = None
   
    def __init__(self, write_connection):
        self.write_connection = write_connection
       
    def __enter__(self):
        self.prev_default = connections['default']
        connections['default'] = connections[self.write_connection]
        return self

    def __exit__(self, *exc):
        connections['default'] = self.prev_default
        return False

Which allows me to overwrite default connection. It is very useful when you use a jupyter notebook and you need to switch between db connections that have different data but the same structure (django models)

But the shared implementation of that context manager stops working recently

ValueError: Subqueries aren't allowed across different databases. Force the inner query to be evaluated using `list(inner_query)`.

But I'm wondering wouldn't it be useful to have that kind of manager in the core Django functionality, or it is a stupid idea?

Thank you

Adam Johnson

unread,
Jun 1, 2022, 9:56:31 AM6/1/22
to Django developers (Contributions to Django itself)
Modifying the connections object seems like the wrong way to approach this, as it's not intended for mutation. Did you consider writing a database router and then having a context manager that affects the router's state? https://docs.djangoproject.com/en/4.0/topics/db/multi-db/#topics-db-multi-db-routing . That is the API Django supports for moving queries to different databases.

--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/ad453105-2116-40c9-a1ff-9571bfb080d1n%40googlegroups.com.

Alexander Lyabah

unread,
Jun 1, 2022, 2:22:45 PM6/1/22
to Django developers (Contributions to Django itself)
That's a great idea, actually. Thank you
Reply all
Reply to author
Forward
0 new messages