Django Tutorial for beginners [step by step] part 4 – Model and database in Django

Tutorial goals: Create a model, migrate it, databases in Django, create a superuser admin, register model.

Welcome to Django tutorial for beginners, tutorial part 4. In this tutorial, we are going to create a Django model, use the Django admin interface, enter some data into the model. Alright, let’s do this. 🙂 

Django model 

A model in Django is a python class defined by Django to represent data and facilitate the creation, update, and management of the data in the database. If you are making a music store website, there are various data like user data (username, emails) product detail (song title, artist, producer, …)  that you need to store. In this case, an artist is an object that has its own properties like name, country, genre, birth year.

The first step in creating a model is to try to identify important properties of a “thing” that we need to store. For example, in the next section, we want to create an “artist” model (Musician). So we need to think about different properties that we may need to know about a specific musician artist. We need to know the name of the person, country, birth date, and genre of music that the person is creating.  We may also want to store eye color, height, gender, city of birth, and basically any “property” that a person may have. But it is a good idea to pick only the essential properties to keep the models simple and useful. 

Create a Django model 

Now we will create the artist model. In the previous tutorial, we created a new Django app (song). Models should be defined inside an app folder in a file named models.py. You can not create models in the main app (“~/musiclibrary/song”).  The main app does not even have a models.py file. But there is a models.py file inside the song app that we created. So open the models.py file of the song app (“~/musiclibrary/song/models.py”) in the editor and add these lines to the file.

from django.db import models

class Artist (models.Model):
    name = models.CharField(max_length = 250)
    country = models.CharField(max_length = 150)
    birth_year = models.IntegerField()
    genre = models.CharField(max_length = 150)

Let’s review the code above line by line. 

In the first line, we import from django.db. The models is the module that has the base class for all of our models. The first line is automatically created by Django when a new app is created. 

Class Artist (models.Model): In this line, we’re defining our artist, or in other words our model of the artist. The special keyword Class is used to define a model which is basically a class. Artist is the name we’re giving to our model. Usually, a model name should start with a capital letter You can name it anything you want but if it’s better to be meaningful and something easy to remember.

Next, we are creating the properties of our model. The first one is the name of the artist. This field is of type (models.CharField) in other words field of characters with max_length of 250. It means that this field could hold up to 250 characters. The type field of the country is the same as the name but with only 150 characters (which is way bigger than any potential country name!). The next stop is birth_year. This field is an IntegerField. As the name suggests, it is an integer for example 1988. The last one is the genre which is just another CharField like name and country. 

Most of the time you will be needed more than one model. Let’s create another model called song as follows:

class Song(models.Model):
    Title = models.CharField(max_length = 250)
    release_date = models.IntegerField()
    length = models.DateField()
    artist = models.ForeignKey('Artist', on_delete=models.CASCADE)

As you can see there is a new field(Foreignkey). What is Foreignkey?

Sometime we have 2 or several models that fields associated with each other. The way we are going to associate models with each other is by using whats known as a foreign key. Foreignkey is a way to associate a record in a model for example artist to another model(in our case the song model). By Foreignkey to the artist model, we can access all the properties of the artist like birth year, genre, etc…in the song model.

Databases in Django 

A database is some information stored in a well-organized way. The purpose of the database is to hold a large amount of data and allow a fast method to store and retrieve specific information. If you’ve decided to be a backend developer, it’s important to know how to interact with the database and how a database works. For example, as your music store website gets bigger, you need to deal with a high amount of data like users data, song, and artist data…, etc. Django by default used a minimal database called SQLite. It means that you don’t have to install any database software to start development. You should not use SQLite in production because it is only for development and testing. Django officially supports the following databases:

 If your project is dealing with a high volume of data you must install a production-ready database server like MySQL even for development. A database setup by itself can be a time-consuming process with various configurations in settings.py and installing packages. For now, we just use SQLite and we are very happy with that. If you open the settings.py file of a Django project you’ll notice the DATABASES section with some settings. Moving on to the next section

Migrations

When we add a model to our models.py file, nothing actually happened until we tell Django that it should check the models and apply changes that we have made to the models.py. This is called migrations in Django’s world. By migrating our models, we make sure that the model definition in models.py files and the actual database are in sync. Also, every change that we make in our model, like adding a new field, should apply to the database too. Migrations take care of these too.

Django migrations are a two-step process. First, we make migrations and then we apply them. Open a terminal and make sure you have activated your virtual environment

python manage.py makemigrations 

The output should look like this:

  —— output ——–

  song/migrations/0001_initial.py
    - Create model Artist

Now it’s time to apply the changes to the database.

python manage.py migrate

This command creates our migration file. This file is an instruction for Django on how to create tables in your database with regard to your models in the app. If you check out the music app directory, you can see that a migration folder has been created, which contains 2 python files:

the output of this command should look like this:

—— output ——–

  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying song.0001_initial... OK
  Applying sessions.0001_initial... OK

What the heck are these?!

Good question! Remember in the part previous part of this tutorial series on Django we created and installed the song app in settings.py under INSTALLED_APPS? There were some preinstalled apps in the settings.py. These preinstalled apps have some models in them, and these models need migrations too. So the first time you migrate your models, Django also migrates its internal models, and the stuff you see in the output above is confirmation that these migrations have been applied. Notice the line before the last line. This is the confirmation that our artist model in the song app has been migrated.

Admin interface

Almost any website has an admin section. Django admin interface is one of the best features of Django. It provides a ready-to-use user interface for administrative activities. No doubt that the admin interface is important for a web project. When you create a Django project, Django automatically generates admin UI based on your project models. It is a helpful tool in adding, removing, or editing models. You can easily do manage your website with the Django admin page and also customize it for your project if necessary. 

Create Admin User (superuser)

When you create a Django project,  Django automatically created and configured the default admin site for you. All you need to do now is create an admin user (superuser) to log in. To create an admin user, run the following command afterward:

python manage.py createsuperuser

Then you will be asked to enter your desired user name:

Username: admin

Enter email address:

Email address: admin@example.com

And finally is to enter your password. Enter your password twice, the second time to confirm your password:

Password: **********
Password (again): *********
Superuser created successfully.

Now you can log in to your Django admin by clicking on the URL in the editor and adding /admin at the end of the link:

django  admin login page

Django admin login page

By entering the user name and password you chose. once you will log in you can see this page:

django admin interface

Django admin index page

You will see Groups and Users that are models of the Django authentication module that hold user and superuser data. Feel free to check it out. 

So what about the song and artist model that we created?! Still another step is remained to be able to manage our models in which is registering the model with Django admin. 

Register Django model in admin

In order for Django models to show up in the admin interface, you need to register them. Open the admin.py in the song app (“~/musiclibrary/song/admin.py”):

from django.contrib import admin
from .models import Artist

admin.site.register(Artist)

Now if you log into the admin interface you can see the music section and model of the artist.

registered model in admin

registered model in admin

This is the end of part 4. I’ll see you in the next part. Thank you for reading. 🙂

If you wish to join a community of self-starters learning new skills and creating projects from scratch, join our Discord channel here and share your passion.

Please do tell us, did you find the content above helpful?