Django - Working with DataBase

Till now in this tutorial series, you have learned more of frontend side work working with HTML, URLs and etc. Now in this tutorial, you will learn about the database. By default, the Django comes with SQLite3 DataBase. Sqlite3 is preinstalled and pre-configured within the Django. You don't have to install it or configure it, but in case if you want to use MySql or Mongo or other DB then you have to configure those. But the syntax of most of the code will remain the same as for Sqlite3.

DB Configuration

Like I mentioned SQLite3 is pre-configured in the Django so you don't have to do any configuration. Configuration path is in file.

The DataBase file name is db.sqlite3 you can find that file in your project folder. This file contains all of your database entries. 

What are Migrations?

In the Django, we create database tables and columns with python code called models. Models contain the entire database structure. When we create a migration python prepare to implement those structures (or changes in structures) in your database. 

When you create a new project, some applications like admin, auth, session already have there migrations ready. So you don't have to create migrations for those apps. 

First Migrate

Once migrations are ready we need to implement those changes in the DataBase with help of Migrate.

First time, when you run your server it gives you a warning that there are some unapplied migrations. That's because we have migrations ready of applications like auth and admin but we haven't implemented those in our database. 

To implement those changes we need to run a command

python3 migrate

After this, you will multiple lines of output that list column names of your database. 

Check your database with any sqlite3 DB browser. You can find a list of columns in your database.

Create a Super User

Once you are done with Migrate. You need to create a superuser so that you can login to your Django admin panel.

To create a Super user just use Django inbuilt tool and run a command

python3 createsuperuser

It will ask you for username, email, and password. Your password should meet the complexity requirement, this is an inbuilt security feature of Django.

The Django Admin Panel

Now you can login to your Django admin panel. Just run the server and browse /admin URL.


For more information, I have attached a video for reference.


About the author



Please login to comment