Hyun Jae Lee
Hyun Jae Lee

Reputation: 17

How to set up multiple schema in django with oracle as a database?

My workplace is planning to use Python/Django as a backend framework and React on the front, on top of oracle db from ASP classic. Since our oracle db structured from the beginning of the company, we decided to keep it as is.

From my understanding, schemas in oracle are typically accessed by username/password, thus need to have user/password for each schema to have an access and our oracle db has about 30ish schemas, containing numerous tables inside for each.

Django, on the other hand, seems it only supports one schema at a time, based on app that is installed in settings.py, which sounds like the databases configuration need to have different user/password set up in settings.py for each app installed.

So far, I've tried class Meta and DATABASES in settings.py;

    // class Meta
    class SomeModel(models.Model):
            ///some fields and data types...

            class Meta():
                    managed=False
                    db_table=u'"schema\".\"table"'

    // DATABASES
    DATABASES = {
          'default': {
                'ENGINE': 'django.db.backends.oracle',
                'NAME': 'multi_schema_db',
                'USER': 'django_user',
                'PASSWORD': 'secret',
          },

          'data': {
                'ENGINE': 'django.db.backends.oracle',
                'NAME': 'multi_schema_db',
                'USER': 'data_user',
                'PASSWORD': 'secret',
          },
    }

My questions is, is there any workaround to have an access into multiple schema where django has only one app installed?

P.S. Correct me on any misunderstandings that I have above.

Upvotes: 0

Views: 2812

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You can have multiple schemas in Django

DATABASES = {
      'default': {
            'ENGINE': 'django.db.backends.oracle',
            'NAME': 'multi_schema_db_1',  # The name is the schema
            'USER': 'django_user',
            'PASSWORD': 'secret',
      },

      'data': {
            'ENGINE': 'django.db.backends.oracle',
            'NAME': 'multi_schema_db_2',  # The name is the schema
            'USER': 'data_user',
            'PASSWORD': 'secret',
      },
}

To use a particular schema you use .using()

SomeModel.objects.using('data').all()  # The default is to use the "default" database conection

If some models are only ever in one schema you can use routers to define which database to use for each model

class YourRouter:

    def db_for_read(self, model, **hints):
        return database_for_the_model

    def db_for_write(self, model, **hints):
        return database_for_the_model

Upvotes: 4

Related Questions