How to Use Another Database for Generating Model in Django Application

Posted on

Introduction

Actually, this article has a specific relation with several previous articles. The first one is the article which is focusing on how to generate model. That one exist in How to Backup or Duplicate Model Class Django Application in Microsoft Windows using inspectdb. But instead using the ‘default’ database exist in he Django Project configuration setting, just use another database. For information about database definition, check out in How to Define Database Configuration in Django Application. As for adding another database, it is exist in another article in How to Define Multi Database Configuration in Django Application. Aside from the ‘default’ database definition, there is another database definition. Below are those definitions in the ‘settings.py’ file as part of the Django project configuration :

# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

DATABASES = {
  # 'default': {
        # 'ENGINE': 'django.db.backends.sqlite3',
        # 'NAME': BASE_DIR / 'db.sqlite3',
  # }

    'default': {
       'ENGINE': 'django.db.backends.postgresql_psycopg2',
       'NAME': 'django_training',
       'USER': 'postgres',
       'PASSWORD': 'password',
       'HOST': 'localhost',
       'PORT': '5432'
    },
    'myapp' : {
       'ENGINE': 'django.db.backends.postgresql_psycopg2',
       'NAME': 'db_myapp',
       'USER': 'postgres',
       'PASSWORD': 'password',
       'HOST': 'localhost',
       'PORT': '5432'
    }
}

How to Use Another Database for Generating Model in Django Application

So, in this case instead of using ‘default’ database connection, just use another database. In that context, it is the ‘myapp’ database definition. So, in order to generate model or backup the model as in the How to Backup or Duplicate Model Class Django Application in Microsoft Windows using inspectdb, just change the command parameter. In the normal parameter which is using ‘default’ database definition, the following is the command :

python manage.py inspectdb --database default auth_user > model_auth_user.py

In the above command, there is a specific parameter. The first one is the database definition which exist as part of the parameter. In this context, –database default. In that case, in order to change into another database, just change the command parameter as follows :

python manage.py inspectdb --database myapp auth_user > model_auth_user.py

Another thing, just change another parameter which is describing the table name exist in the database. So, just check the table available in the database. For an example, since ‘auth_user’ is also a default table exist in the Django project or Django application just execute the above command as is.

Leave a Reply