3

Is there a way I can tell Django2 to use a different database (and cache/session store) depending on a parameter in the URL?

Note that I have read the docs related to multiple databases en Django (https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#automatic-database-routing), and that is not what I'm asking.

The docs are showing an example about how to use DATABASE_ROUTERS, which is a way of choosing which database should be used programatically when using a model.

What I'm asking is how can I make Django2 use different databases automatically depending on a parameter in the URL. Example:

http://foo.bar/usa      <-- use USA database
http://foo.bar/europe   <-- use Europe database

Edit: to whoever is marking this question as duplicate.Please read carefully what I'm asking.

First of all, I'm asking to do this automatically, versus the programatically solution that was provided as an answer in Django - Runtime database switching

Second, I'm asking for database, session/cookies and cache storage, which is quite different than just changing the database for model queries.

alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • If you have 2 databases, do you have the same models in both? Is it just a duplicate system with different data? If that is the case, wouldn't it be easier to just have 2 different webservers that use the app code? – Ralf Sep 18 '18 at 22:36
  • Possible duplicate of [Django - Runtime database switching](https://stackoverflow.com/questions/30226604/django-runtime-database-switching) – Karim N Gorjux Sep 18 '18 at 22:36
  • Yes, exactly the same models, just entirely different content. No, it won't. I have reasons to be asking for this, which are out of the scope of this question. – alexandernst Sep 18 '18 at 22:36
  • @KarimNGorjux not duplicate. I'm asking for cache/session store also. Might be semi-related. – alexandernst Sep 18 '18 at 22:39
  • Have you tried adding a middleware or a mixin/logic to the view that based off of the url parameter will override global settings. You can override any setting you'd like via that method. You'd import the settings via `django.conf and override with something like `with settings.CACHE = []:` but I think that's a hackish solution that might get in your way when scaling. Abusing global variables is never a good thing. Could you possibly explain as to why you'd need this solution, because we might offer a different solution? – Borko Kovacev Sep 18 '18 at 23:34
  • @BorkoKovacev the entire mixin/middleware logic sounds like a very hacky solution (that also might involve threading.local(), which is as bad as it gets). Think about my app/problem as a shopify store. I want to have a single codebase, but each "client" should have it's own store (with it's own categories, products, listings, stock, etc...). – alexandernst Sep 19 '18 at 08:48

0 Answers0