Your first model - 30 days of Django

Your first model - 30 days of Django

/ #Django


Let's set up the database model for the tasks and learn a little bit about our choices.

What is a database model?

A database model is used to describe to a database what information we want to store there, and also to make functionality to interact with it. It's probably easier to understand if I show you the database for the tasks first.

Database model for the tasks

Open up "task/models.py" and add the following there.

class Task(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True, null=True)
    is_done = models.BooleanField(default=False)

Okay, we don't need anything more there yet.

First, we create a new class with the name of the model and pass in "models.Model" to tell Django that we're using this class. Then, inside the class, we define three different fields to the model. As you can see, there are different field types (and there are of course many more as well).

The CharField is usually used for shorter strings like titles, names, addresses and similar. The TextField is used for longer texts. As you can see, we pass in "blank=True, null=True". This is to allow the field to be empty/optional. The title doesn't have this, so if you try to add a task without it, you will get an error.

For the last field, we use a BooleanField (True/False) to make it possible to track if a task is done or not. The default value will be set to False.

Updating the database

Everytime we create a new database model or make a change to it, we need to update the database. Don't worry this is just two simple commands.

$ python3 manage.py makemigrations

When you run this command, Django will create some new files for us. The files contains information about the database model we created. It's just a more low level Python script about the SQL. Next, we just need to execute the migration scripts.

$ python3 manage.py migrate

When this is done, a new table should have been created in the database and we're ready to continue.

Summary

For many people, the concepts of models/databases/migrations can be a little bit confusing. Do make it a little bit easier to understand, I skipped going into the migrations files for now. It's just not very important for beginners to understand (in my opinion).

We will work more with models and it's functionality later in this tutorial series.

Table of contents

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.