Your First Model
Now you have an idea what Django models are, it’s time to create your first model.
The MyClub website application includes an event planner. In the last chapter, we created the events
app to manage events within our MyClub web application. If you haven’t created the events
app yet, you need to go back to Page [ref] and create it now.
DB Browser for SQLite
Throughout this chapter, and in a few other chapters, I will use an application called DB Browser for SQLite. This is an excellent tool for checking out what is going on inside your SQLite database as Django changes things.
If you want to install DB Browser for SQLite on your machine, you can download it from https://sqlitebrowser.org/
.
There is lots of information we can record for a club event, but we will start with a basic event model. When you are first designing a data model, it’s always an excellent idea to map out the table fields before you create the model.
There are many approaches to mapping out data structures—from simple tables to complex data maps using special markup. As you have probably worked out by now, my preference is to keep things as simple as possible, so I tend just to use tables (Table 4.1).
Field Name | Field Description | Data Type |
---|---|---|
name | Name of the event | Short Text |
date | Date and time of the event | Date/Time |
venue | Location of the event | Short Text |
manager | Name of the person managing the event | Short Text |
description | Detailed description of the event | Long Text |
Table 4.1: A simple mapping of our event
model fields.
This should be straightforward—we have database-friendly names for the fields, a description of the field, and the data-type to save to the field in the database. The description is for your benefit when you come back to the model later and need to remind yourself what the field was for. You can also put the field description in your model as comments or in the model’s docstring. We won’t be adding comments or docstrings to our code in this book; just keep it in mind for when you become a professional programmer—properly documenting your code is a Good Thing.
Now let’s turn our table into a Django model. Open the models.py
file in your events
folder and add the following model code:
# \myclub_root\events\models.py
1 from django.db import models
2
3 class Event(models.Model):
4 name = models.CharField('Event Name', max_length=120)
5 event_date = models.DateTimeField('Event Date')
6 venue = models.CharField(max_length=120)
7 manager = models.CharField(max_length=60)
8 description = models.TextField(blank=True)
Let’s have a closer look at your first model, as a fair bit is going on here:
- Line 1 imports the
models
package fromdjango.db
. If you usedstartapp
, this line will already be in your file. - Line 3 is the
Event
class definition. Each Django model must inherit from Django’sModel
class.
Each of our model fields has a related Django field type and field options. The Event
model uses three different field types—CharField
, DateTimeField
and TextField
. Let’s have a look at the field types and options in more detail:
- Line 4. The
name
field is a DjangoCharField
. ACharField
is a short line of text (up to 255 characters). Here, themax_length
option sets the maximum length of the event name to 120 characters. Thename
field also has a verbose name argument. The verbose name is used to create a human-friendly name for the model field. Most model fields accept verbose name, either as the first positional argument or as a keyword argument (verbose_name
). - Line 5.
event_date
is a DjangoDateTimeField
. ADateTimeField
records a Pythondatetime
object. Theevent_date
field has a single argument—the verbose name for the field. Note that I have named the fieldevent_date
, rather than justdate
. This is to avoid confusion with Python’sdate()
function. Django will let you use function names and Python reserved words in field names, but it’s always best not to. - Lines 6 and 7.
venue
andmanager
are both DjangoCharFields
. As themax_length
argument is required onCharFields
,max_length
is set to limit the size of the field. - Line 8.
description
is a DjangoTextField
. ATextField
is a large text field that can hold many thousands of characters (maximum depends on the database). The final option—blank=True
—is set so we can create an event without a detailed description. The default for this option isFalse
; if you don’t add a description, Django will throw an error.
This simple event model only uses a small subset of the model field types and options available in Django. We’ll be using many more throughout the book. There is also a complete reference to all the model fields and options in the Django documentation.
Now we’ve created the model, it’s time to add it to the database. Make sure the virtual environment is running and then change into the myclub_root
directory. From your command prompt, run:
python manage.py makemigrations
Hit enter and then run the command:
python manage.py migrate
Your terminal output should look something like this:
(env_myclub) ...\myclub_root> python manage.py makemigrations
Migrations for 'events':
events\migrations\0001_initial.py
- Create model Event
(env_myclub) ...\myclub_root> python manage.py migrate
Operations to perform:
Apply all migrations: events
Running migrations:
Applying events.0001_initial... OK
This is all you need to do to add your new model to the database. Before we go on though, remember how I said Django uses the model to generate SQL? Try this command at your command prompt:
python manage.py sqlmigrate events 0001_initial
You should get an output that looks like this (I’ve reformatted the output for clarity):
BEGIN;
--
-- Create model Event
--
CREATE TABLE "events_event" (
"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
"name" varchar(120) NOT NULL,
"event_date" datetime NOT NULL,
"venue" varchar(120) NOT NULL,
"manager" varchar(60) NOT NULL,
"description" text NOT NULL
);
COMMIT;
The sqlmigrate
command prints the SQL for the named migration. Here, it’s printing out the SQL for the initial migration, where Django creates the new table and adds the fields to the table.
We can check out what Django created in the database browser (Figure 4.4).
Figure 4.4: The event table in the database.
You can see Django’s app_model
naming convention for table names at work in the table name (events_event
). Also, note how each model field is added as a table field with the appropriate data-type applied. If you are using DB Browser for SQLite, you will also notice the schema for the table is almost the same as the SQL the sqlmigrate
command printed out.
Finally, note that the SQL, data-types and database schema are different for each database type. This is what’s so cool about Django’s models—most of the time, you don’t have to worry about the underlying database when creating your models.
There are some quirks relating to individual database engines, but this is advanced stuff beyond the scope of this book. If you want to check out the notes on individual database engines, see the Django documentation.