Django Database: How to Connect SQLite Database with Django Project

We learned about Django Models in the last tutorial, and now we’ll go through how to connect a database to a Django project.

We want some form of input from our end-users or consumers whenever we create a web application or any kind of project. A database manages all of that data and input.

In today’s world, we’ll need a database every time we build a website, whether it’s a simple Library management site or a highly interactive one like Instagram. To do so, you’ll need software that can efficiently store the data as well as middleware that allows you to interact with the database.

Connecting Database with Django Project

When we created our first app and started the server, you should have noticed a new file named ‘db.sqlite3′ in your project directory. The file is a database file that will keep all of the data that you will be generating. Since Django is a server-side framework, it treats your computer as the host when you run the server from the command line or terminal.

This file is generated automatically since Django’s database is set to SQLite by default, which is good for testing and has a lot of functionality, but if you want your website to be scalable, you can convert it to a more efficient database.

In our case, we’ll be using SQLite, and this tutorial will show you how to integrate SQLite into your project.

Don’t worry, you don’t need to learn SQL because all of the backend code is written in Python, which is a Django Model advantage.

DATABASES Dictionary Indexes

To begin, find this section in the settings.py file of your web application/project.

Database Dictonary Indexes

This segment contains information about the database connection.

DATABASES is a pre-defined dictionary in Django Framework, with the value for the main database where all the data will be saved as an index.

There can be several databases because we require data backups as well, but there is only one default database, and we won’t be introducing any more databases for the time being.

The default store a dictionary with two indexes:

ENGINE

When connected to a certain website, it specifies the library to be used. We must include the file “django.db.backends.sqlite3” in the value, which is a python library for the sqlite3 database that will convert your python code to the database language.

As a result, you won’t need to learn any additional database languages because all of the code is written in Python.

Django ENGINE values for various databases

Database Django ENGINE value Required package
MySQL “django.db.backends.mysql” None, it’s included with Django
MariaDB “django.db.backends.mysql” None, it’s included with Django
Oracle “django.db.backends.oracle” None, it’s included with Django
PostgreSQL “django.db.backends.postgresql_psycopg2” None, it’s included with Django
SQLite “django.db.backends.sqlite3” None, it’s included with Django
SAP (Sybase) SQL Anywhere “sqlany_django” “pip install sqlany-django”
IBM DB2 “ibm_db_django” “pip install ibm_db_django”
Firebird “firebird” “pip install django-firebird”

NAME

The name of the database you’re using, as well as its location, are here. The value of this parameter varies depending on the database you’re using. You can play around with the database file here.

We’re also supplying the database file name, or if one doesn’t exist, the db.sqlite3 file will be created. If you rename the file to db1.sqlite3 or something else, it will be created in your root directory every time you run the server.

Connection options for Django databases based on database brand

Django connection parameter Default value Notes
ATOMIC_REQUESTS False Enforces (or not) a transaction for each view request.The impact on performance is determined by an application’s query patterns and the database’s ability to handle locking.
AUTOCOMMIT True As commits would otherwise require explicit transactions, the value is set to True by default.
CONN_MAX_AGE 0 By default, the database connection is closed at the end of each request. Use None to create an unlimited number of persistent connections.
DISABLE_SERVER_SIDE_CURSORS False Disable the use of server-side cursors in PostgreSQL, which is useful in cases involving databases.
ENGINE ”(Empty string) Have a look at the previous table.
HOST ”(Empty string) A database host is defined by an empty string, which signifies localhost. If this value begins with a forward slash (‘/’), MySQL will connect to the specified socket via a Unix socket (e.g., “HOST”: ‘/var/run/mysql’). This value is presumed to be the host if it does not begin with a forward slash. For PostgreSQL, the database connection is made by default(“) using UNIX domain sockets (‘local’ lines in pg hba.conf). Use the same value of unix socket directory from postgresql.conf if the UNIX domain socket is not in the standard location. Set HOST to ‘localhost’ or ‘127.0.0.1’ (‘host’ lines in pg hba.conf) if you want to connect using TCP sockets. Because UNIX domain sockets are not available on Windows, you should always define HOST.
NAME ”(Empty string) The database name that will be used. It’s the complete path of the database file in SQLite. Even on Windows, always use forward slashes when specifying the path (e.g. C:/www/STORE/db.sqlite3).
OPTIONS {} (Empty dictionary) When connecting to the database, there are certain additional parameters to use. The available parameters differ based on the database brand; visit the documentation for the Django database engine module for further information. 
PASSWORD ” (Empty string) When connecting to the database, this is the password to use. SQLite is not supported.
PORT ” (Empty string) When connecting to the database, this is the port to use. The default port is represented as an empty string. SQLite is not supported.
TEST {} (Empty dictionary) Defines database connection parameters for use in a Django project’s test database, similar to those given in this table.
TIME_ZONE None (Empty) For date times saved in a database, this property specifies the time zone. A rarely used option for storing times in a local timezone rather than UTC in database records.
USER ” (Empty string) When connecting to the database, this is the username to use. SQLite is not supported.

SQLite and Django – Connecting SQLite Database with Django Project

The SQLite is a free, open-source, public-domain software package that provides a relational database management system (RDBMS). RDBMS are database management systems that hold user-defined records in big tables. A database engine can perform complicated query commands that integrate data from numerous tables to generate reports and data summaries in a data storage and management system.

Here are the steps to integrate the Django project with MySQL:

1. Install DB Browser

DB Browser for SQLite is an open-source, high-quality visual tool for creating, developing, and modifying SQLite-compatible database files. Users and developers who want to create, search, construct, and edit databases will find it useful. There is no need to learn sophisticated SQL statements because the SQLite browser employs a spreadsheet-like interface.

It’s a tool that’s used by both developers and end-users, therefore it needs to be as simple as possible. Depending on your operating system, download SQLite standard installation.

Install DB Browser

2. Changing the settings.py file

The first step in setting our database is to inform Django that we have added an application to our project that requires some configuration. To accomplish this, go to our internal site directory’s settings.py file and add the following line to the installed apps section:

 

3. Migrations

Django has its version control mechanism, which is known as migrations. When you make a change that requires any new dependencies to be installed, you must tell django from the command line. Each modification you make will be noted as a migration, which you can review later, to go back to prior versions.

Use the following command to instruct Django to begin creating our database (make sure you are in the directory containing manage.py).

python manage.py migrate

Django database Settings

Tables for admin, auth, contenttypes, and sessions will be created with this command.
Just keep in mind that Django requires these migrations to offer some fundamental functionality.

Now you may access the SQLite database and see it from the database list. The following tables are there in the database.

Django Database Settings

4. Defining Models

We need to define some models for storing information, now that our database has been set up. To do so, go to our application folder and look for models.py.

When we define a model, we simply construct a class that is the name of our model that inherits from models.Model.Then, as class variables, we declare all of our model’s fields or attributes. We can also add methods to our models to use.

from django.db import models

# Create your models here.
class Employee(models.Model):
    Empid= models.IntegerField()
    name= models.CharField(max_length=25)
    address= models.CharField(max_length=100)
    salary= models.IntegerField()
    Department= models.CharField(max_length=25)

5. Making Migrations

We need to notify Django to update our database now that we’ve modified our models file. We use the following command to implement this:

python manage.py makemigrations

Finally, we apply the following to execute the migrations:

python manage.py migrate

In the terminal, type the following command.

python manage.py sqlmigrate Employee 0001

You’ll come into something similar to this.

Django DataBase Migrations

6. Open the DB Browser (SQLite)

Activate the DB Browser

Now go to the directory where you saved your project and click on the ‘Open Database’ button (TechVidvan2). Choose the ‘db.sqlite3′ file.

So there you have it, the newly generated table. Now it contains the Employee table.

Django DB Browser

Django Database Connectivity

As you can see, the database has a table. So, we’ve successfully connected our Django application to the SQLite database.

Summary

We learned how to add an SQLite database to our project and how to use the Django Framework’s DATABASE dictionary.

We also discovered that Django includes middleware and libraries for every major database. And you don’t have to learn a new database language because Django takes care of everything.

If you are still confused with any of the concepts, please ask your queries in the comments section.