[Fixed]-Dynamic database selection based on URL in Django

1👍

So you need to store the chosen database in session or smth and you can easily pick the database. From the docs

>>> # This will run on the 'default' database.
>>> Author.objects.all()

>>> # So will this.
>>> Author.objects.using('default').all()

>>> # This will run on the 'other' database.
>>> Author.objects.using('other').all()

0👍

You could mix together Database Routers with this GlobalRequestMiddleware solution to create a database router which inspects the request to figure out which database to use.

class RequestDatabaseRouter(object):
  def db_for_read(self, model, **hints):
    request = GlobalRequestMiddleware.get_current_request()
    key = self.get_database_key(request)  # Implement get_database_key
    return key

There may be some way to inject the request into **hints, which I think would be preferable over the Middleware solution, however, I’m unaware how to at the moment. You may need to make sure the GlobalRequestMiddleware is called after the AuthenticationMiddleware otherwise you may not have the user on the request to inspect.

Leave a comment