Multiple database implementation in Django

  1. Define database connections in myproject/settings.py:
    DATABASES = {
        'default': {
            'NAME':  'db1',
            'ENGINE':  'django.db.backends.mysql',
            'USER':  'myuser1',
            'PASSWORD':    'mypass1',
        },
        'my_db_2': {
            'NAME':  'db2',
            'ENGINE':  'django.db.backends.mysql',
            'USER':  'myuser2',
            'PASSWORD':    'mypass2'
        }
    }
  2. Define router in myproject/myapp2/routers.py:
    class MyApp2Router(object):
        """
        A router to control all database operations on models in
        the myapp2 application
        """
    
        def db_for_read(self, model, **hints):
            """
            Point all operations on myapp2 models to 'my_db_2'
            """
            if model._meta.app_label == 'myapp2':
                return 'my_db_2'
            return None
    
        def db_for_write(self, model, **hints):
            """
            Point all operations on myapp models to 'other'
            """
            if model._meta.app_label == 'myapp2':
                return 'my_db_2'
            return None
    
        def allow_syncdb(self, db, model):
            """
            Make sure the 'myapp2' app only appears on the 'other' db
            """
            if db == 'my_db_2':
                return model._meta.app_label == 'myapp2'
            elif model._meta.app_label == 'myapp2':
                return False
            return None
    
    This is pretty much a copy and paste job from the official example. The one key point left out was where to define this. It turns out that myapp2/models.py is not the right place and something like myapp2/routers.py is!
  3. Now all that remains is to tell our project about the router. In myproject/settings.py add:
    DATABASE_ROUTERS = ['myapp.routers.MyApp2Router',]
    
You can see that throughout I am only concerned with my second app (myapp2). This is because, for the time being myapp1 would use the default database router which comes out of the box with Django. Of course at some point I may well need another router for that app or an additional one, which is when I could define I new router, hook it up to said app and add the router path to the settings.

No comments:

Post a Comment