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 varible "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 dabases 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 deatils 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.

That's it folks, we have seen how to configure the database settings in the django application. In the next article we can see how to create a table in the database using django ORM models.

 

Support Me on Patreon