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.
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
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page