Skip to content
Advertisement

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 settings.py file I have this:

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

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.

Advertisement

Answer

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:

MyCustomModel.objects.filter(username=logged_in_username)

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

7 People found this is helpful
Advertisement