Django Database

Learn via video courses
Topics Covered

Overview

Django is a high-level Python web framework that allows the rapid development of secure and maintainable websites. It is free and open source. Django supports some of the standard Database programs like PostgreSQL, SQLite, MySQL, etc.

Prerequisites

Before moving on to Django Database connections, you must first meet the following prerequisites:

  • A web server.
  • A Database application. Here we will be using MySQL.
  • Python environment set up.

django-database-supported-database

Set up a Django Database

First, let us see what a Database means. Well, a Database is nothing but a collection of data in an organized manner. It is also known as structured data. Django supports some of the standard Database programs like PostgreSQL, SQLite, MySQL, etc. The Django configuration to connect to a Database is done in the Django project's settting.py file in the DATABASES variable. A detailed explanation of the DATABASES variable is given in this article further.

Setting up a Database in Django takes a considerable amount of time. SQLite is by default installed in Python. We also have the option to leave the setting unchanged and continue with SQLite. When installing SQLite, no additional Python packages are required.

Databases Supported by Django

Some Databases are already included in Django, which means they are officially supported by Django. These include:

  • MySQL
  • PostgreSQL
  • MariaDB
  • Oracle
  • SQLite

Certain relational Databases are unofficially supported by Django. Some of them are:

  • Google Cloud Spanner
  • Firebird
  • Cockroach Database
  • IBM DB2
  • SAP (Sybase) SQL Anywhere
  • Microsoft SQL Server & Azure SQL

Default Django DATABASES Dictionary

DATABASES is a pre-defined dictionary found in thesetting.py file, with the index 'default' holding the value for the main Database where all data is to be stored.

In the above code,

  • We observe that in the variable DATABASES, each key is a database reference name, and the value is a Python dictionary containing the Database connection parameters..
  • The default Database connection parameters are the keys ENGINE and NAME.
  • ENGINE denotes a database engine, and NAME denotes the name of a database instance.

The most important parameter of the Django Database connection is ENGINE. We can always write Database CRUD operations in the same way, regardless of the Database used, demonstrating that the Django application logic associated with the Database is platform agnostic.

Django ENGINE Value for Different Databases

Listed below are the ENGINE values of Databases officially supported by Django:

DatabaseDjango ENGINE value
MySQLdjango.db.backends.mysql
PostgreSQLdjango.db.backends.postgresql_psycopg2
MariaDBdjango.db.backends.mysql
Oracledjango.db.backends.oracle
SQLitedjango.db.backends.sqlite3

Listed below are the ENGINE values of Databases unofficially supported by Django:

DatabaseDjango ENGINE valueRequired Django package
Cockroachdjango_cockroachdbdjango-cockroachdb
Google Cloud Spannerdjango_spannerdjango-google-spanner
Firebirddjango.db.backends.firebirddjango-firebird
IBM DB2ibm_db_djangoibm_db_django
SAP (Sybase) SQL Anywheresqlany_djangosqlany_django
Microsoft SQL Server & Azure SQLmssqlmssql-django

Django Built-in Database Connection Parameters

Apart from the ENGINE and NAME connection parameters other parameters also influence the connection of Django with the Database.

Applicable forDjango connection parameterDefault Value
All DatabaseATOMIC_REQUESTSFalse
All DatabaseAUTOCOMMITTrue
All DatabaseCONN_MAX_AGE0
All DatabaseENGINE'' (Empty string)
All DatabaseHOST'' (Empty string)
All DatabaseOPTIONS{} (Empty dictionary)
All DatabaseNAME'' (Empty string)
All DatabasePASSWORD'' (Empty string)
All DatabasePORT'' (Empty string)
All DatabaseTEST{} (Empty dictionary)
All DatabaseTIME_ZONENone (Empty)
All DatabaseUSER'' (Empty string)
PostgreSQL databasesDISABLE_SERVER_SIDE_CURSORSFalse

Creating the Database

In this section, we will learn how to connect MySQL to Django. Let us begin by starting the command prompt. Before we begin we should make sure that we have MySQL server 5.7+ and Python 3.0+ already installed in our system. If not then it must be downloaded from the official website. The following are the steps to connect MySQL to Django.

  1. We begin by creating and activating the virtual environment and setting up the Django project. We give a (.) at the end of the command, to ensure that the project is created in the working directory. If this is not included then the project will be created in the new directory named data where all Django files will be contained.
  1. We need to use the migrate command.
  1. Now we start the server.
  1. A link will be displayed in the terminal http://127.0.0.1:8000, visit it.
  2. We will be using a MySQL shell.
  3. Let us connect the MySQL server. The following command is to be entered. Enter the password and we are done with the installation.
  1. We create a Database named mydata using the following query.
  1. Once we have created the Database, we need to update the DATABASES section in settings.py .

In the above code, • We need to write 'django.db.backends.mysql' in the ENGINE. • Name indicates the name of the database we use. • User is the username that has access to the Database. • Password is the password of the database. • HOST and PORT indicate hostname and port number. • SET sql_mode='STRICT_TRANS_TABLES' is used to handle the invalid or missing values from being stored in the database by INSERT and UPDATE statements.

  1. Mysqlclient is supposed to be installed now, it is the Python interface to MySQL that permits the Python project to connect to the MySQL server.
  1. We need to create tables in the newly created Database, by running the migrate command. This command will create necessary tables such as auth_group, auth_user, auth_permission, etc., and also create the tables defined in the models.py file.

Test Django Database Connection and Build Django Base Table

After updating the Database credentials in the settings.py file, we can check if the Django application can connect with the Database. The most common method is the Django Database migration process. It ensures that the Database has the necessary tables. We run the migration process to check the connection of Database with the Django and also to create the base table. We use the following command to start the migration.

After running the following command, Django uses a series of migrations to create Database tables to manage a project's users, groups, permissions, and sessions. This ensures that the connection of the Database is successful.

Conclusion

Hello Developer! I am sure by now you must be having a clear idea about setting up a database in Django. Now its time for us to summarize what we have learned so far

  • Django supports some of the standard database programs like PostgreSQL, SQLite, MySQL, etc.
  • A database is a collection of data in an organized manner. It is also known as structured data.
  • The Django configuration to connect to a database is done in the Django project's setting.py file in the DATABASES variable.
  • DATABASES is a pre-defined dictionary, found in the setting.py file with the ‘default’ as an index having the value for the main database where all the data is to be stored.
  • ENGINE is the most important parameter of the Django database connection.