django database connectivity

django database connectivity

Django supports various relational databases like SQLite, mySQL, PostgreSQL, Oracle. Django is completely designed for Relational Databases so it does not support non-relational databases like mongoDB directly. But we can use non-relational databases using third party packages. Let's get started with connecting databases to django application.

All django project configurations can be found in the "settings.py" file. We configure the database settings in a variable "DATABASES" it's a simple dictionary which holds the configurations of the database. When we create a new django project it comes with SQLite database configurations. In order to other databases we have to configure the settings based on the database type like MySQL, PostgreSQL, etc. The "DATABASES" setting must configure a "default" database. We can use multiple databases with django.

Connecting "SQLite" with django

SQLite is a simple file based database and not recommended in the production environment. Let's see it's database configurations

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.sqlite3',
    'NAME': 'database_name'
   }
}

Connecting "MySQL" with django

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'database_name',
    'USER': 'database_user',
    'PASSWORD': 'secret',
    'HOST': '127.0.0.1',
    'PORT': '5432',
  }
}

Connecting "PostgreSQL" with django

DATABASES = {
  'default': {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': 'database_name',
    'USER': 'database_user',
    'PASSWORD': 'secret',
    'HOST': '127.0.0.1',
    'PORT': '5432',
  }
}

Let's see the details of above configuration.

  • ENGINE: The database backed to use.
  • NAME:It's the name of the database.
  • USER: It's the name of the database user.
  • PASSWORD: It's the password for the database user.
  • HOST: It's the IP address of the database server.
  • PORT: It's the port number for the database server.