multiple database

when handling [[multiple database]] is a bit confusing.

Steps

1. Setup the configs in settings

DATABASES = {  
    'default': {  
        'ENGINE': 'django.db.backends.postgresql_psycopg2',  
        'NAME': config.get('database', 'DB_NAME'),  
        'USER': config.get('database', 'DB_USER'),  
        'PASSWORD': config.get('database', 'DB_PASSWORD'),  
        'PORT': '5432',  
        'HOST': 'localhost'  
    },  
    'supabase': dj_database_url.config(  
            default="postgres://postgres.swfrseoejtwvwdlanvrm:UCY:[email protected]:5432/postgres", conn_max_age=600  
        )  
}

2. Setup [[database]] router as per need

class SecondaryDBRouter:  
    def db_for_read(self, model, **hints):  
        # Use the secondary_db for the specific app  
        if model._meta.app_label == 'supabase':  
            return 'supabase'  
        return 'default'  
  
    def db_for_write(self, model, **hints):  
        # Use the secondary_db for the specific app  
        if model._meta.app_label == 'supabase':  
            return 'supabase'  
        return 'default'  
  
    def allow_relation(self, obj1, obj2, **hints):  
        # Allow relations between different databases  
        return True  
  
    def allow_migrate(self, db, app_label, model_name=None, **hints):  
        # Allow migrations on both databases  
        # migarte supabase app to supabase database        if db == 'supabase':  
            return app_label == 'supabase'  
        return True

3. import the router

DATABASE_ROUTERS = ['apps.supabase.router.SecondaryDBRouter']

That Should be it. the things should work

Edge case

Make sure to specify the database while running migrations and optionally app

python manage.py migrate supabase --database=supabase

Last updated