Django Tutorial for Beginners [Step by Step] – Part 4: Model and Database in Django
Welcome to Part 4 of our tutorial series. In this tutorial, we are going to create a Django model, use the Django admin interface, and enter some data into the model.
Our goals for this tutorial are to create a model, migrate it, learn about databases in Django, create a superuseradmin, and register model.
Alright, let's get right to it.
Prerequisites
- Knowledge of creating a basic Django project
- Knowledge of Django's Model-View-Template (MVT) architectural pattern
Refer to parts 1, 2, and 3 of this tutorial series to get a basic understanding of the above.
Django Model
In Django, a model is a Python class that represents data and provides an easy way to create, update, and manage that data in the database. For example, in a music store website, we might store various types of data, such as user information (username, email) and product details (song title, artist, producer). Each of these data points represents an object, like an artist, which has properties such as name, country, genre, and birth year.
The first step in creating a model is to identify the key properties of the "thing" you want to store. For instance, if you're building an "Artist" model, think about the properties that are essential for an artist. You might want to store their name, country, birthdate, and genre of music. Additionally, you may want to record other details such as eye color, height, gender, or city of birth. However, it's a good idea to keep your models simple and focus on the essential properties.
Creating a Django Model
Now, let's create the Artist model. In the previous tutorial, we created a new Django app named song.
Models are defined inside an app's models.py file, so you’ll need to create or edit the models.py file within the song app folder. You can't create models in the main app (musiclibrary), as it doesn't have a models.py file. But inside the song app, you will find models.py.
Open models.py in the song app (~/musiclibrary/song/models.py) and add the following code:
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 break down the code:
- Importing the models module: The first line imports the models module from django.db. This module provides the base class for all Django models, and it’s automatically included when a new app is created.
- Defining the Artist class: In the second line, we define the Artist model as a subclass of models.Model. In Django, the class keyword is used to define a model, and Artist is the name of our model. Model names should start with a capital letter and be descriptive.
- Defining model properties:
- name: This property is a CharField, meaning it stores character data. It has a max_length of 250, meaning it can hold up to 250 characters.
- country: Like the name, this field is also a CharField, but with a max_length of 150, which is more than enough to fit any country name.
- birth_year: This is an integer field, which stores integer data, such as the artist’s year of birth (e.g., 1988).
- genre: This is another CharField with a max_length of 150, used to store the genre of music the artist creates.
Typically, you’ll need more than one model for your application. Next, we’ll create another model for the song using the code below:
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).
So what exactly is Foreignkey?
Sometimes, we have two or more models with fields that are associated with each other. To establish this relationship, we use a concept known as a ForeignKey. A ForeignKey allows us to create a connection between records in different models. For example, if we have an Artist model and Song model, a ForeignKey in the Song model can link each song to a specific artist.
By adding a ForeignKey to the Artist model in the Song model, we can easily access all the properties of the artist (such as birth year, genre, etc.) directly from the song. This relationship ensures that each song is linked to one artist, but an artist can have multiple songs.
Databases in Django
A database is a structured system for storing large amounts of data and enables fast methods to retrieve and manage specific information. As a backend developer, understanding how to interact with a database is crucial, especially as your application grows. For instance, in a music store website, you’ll need to manage a variety of data like user accounts, songs, and artist details.
By default, Django uses SQLite, a lightweight database that doesn’t require additional installation. While SQLite is perfect for development and testing, it isn’t suitable for production environments because it's for development and testing purposes.
Django officially supports several databases for production use:
- MySQL
- MariaDB
- PostgreSQL
- Oracle
For projects that deal with high volumes of data, it’s recommended to use a production-ready database like MySQL, even during development. Setting up a database, configuring it in settings.py, and installing necessary packages can be time-consuming, so for now, we’ll stick with SQLite for simplicity.
If you open the settings.py file of a Django project, you’ll see the DATABASES section with some settings.
Migrations in Django
In Django, when you add or modify a model in models.py, no changes are made to the database until you tell Django to apply them by checking the models.
This process is known as migrations. Migrations ensure that the database schema stays in sync with your models.
Django’s migration process involves two steps:
- Creating a migration file that contains the instructions on how to update the database. This is making the migration.
- Applying the changes in the migration file to the actual database.
Open a terminal and make sure you have activated your virtual environment, then use the following command to make the migration:
python manage.py makemigrations
The output should look like this:
song/migrations/0001_initial.py
- Create model Artist
Once the migration file is created, the next step is to apply the changes to the database using the following command:
python manage.py migrate
This command will apply all migration files to your database, including the initial setup and any changes made to the models.
If you check out the music app directory, you can see that a migration folder has been created, which contains 2 python files.
Here’s an example of what the output might look like:
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
Remember in the 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.
Django Admin Interface
Most websites have an admin section for managing content and user interactions. One of Django’s best features is its built-in admin interface, which provides a ready-to-use UI for admin tasks. The Django admin panel allows developers to add, edit, and delete model records with minimal setup. The interface is also highly customizable to suit specific project needs.
Creating an Admin User (Superuser)
When you create a Django project, Django automatically sets up the default admin site. However, to access it, you need to create a superuser account. This user will have full access to the admin panel.
To create a superuser, run the following command in your terminal:
python manage.py createsuperuser
You will be prompted to enter the following details:
Username: admin
Email address: admin@example.com
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.
Enter the superuser credentials you just created, and you’ll have full control over your Django project’s data through the admin interface.
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? We have to complete one more step to be able to manage our models, 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”) and add these lines of code:
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.
This is the end of the Django tutorial, part 4. I'll see you in the next part.
Next:
Django Tutorial for Beginners [Step by Step] – Part 5: Creating URL, View, and Template.
If you wish to join a community of self-starters learning new skills and creating projects from scratch, join our Discord channel and share your passion.