How do I route my databases in Django based on which user is logged in?


I am making a django website and I want each user to have their own database, for example now I have 2 databases hosted on azure, and in my file I have this:

    'default' :{},
    'user1': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME' : 'temp monitoring',
        'USER' : 'maxwhitehead@maxiot',
        'PASSWORD' : '#######',
        'PORT' : 3306,
        'HOST' : '',
        'ENGINE': 'django.db.backends.mysql',
        'NAME' : 'temp monitoring',
        'USER' : 'maxwhitehead@maxiot2',
        'PASSWORD' : '#######',
        'PORT' : 3306,
        'HOST' : '',

I have a folder called users, and within that I have a file called Fields that includes this:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['username','email','password1','password2']

So I want people to login and see the posts from their associated database. I know I have to do something with database routing but I am not sure what, any help would be appreciated, thanks.


If I may ask, why are you using different databases for each user? If the goal is simply to have each user retrieve only their information you could achieve identical results by having one database and retrieving the user’s information from the database using their username to filter your models. So each model would have a username field and you could retrieve user specific data from that table with something like:


This also has the advantage of being able to scale much more easily as you add users.

If you absolutely need to have separate DBs per user it looks like you could use a Djano DATABASE_ROUTER, but in the documentation that looks like it only handles routing on an app by app basis and doesn’t provide any more narrow granularity than that.

More information on database routing can be found here

Django Database Routing

You could also have an if statement to manually select the database based on the logged in user

Manually Selecting a Django Database

Answered By – CSEngiNerd

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published