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 NameField DescriptionData Type
nameName of the eventShort Text
dateDate and time of the eventDate/Time
venueLocation of the eventShort Text
managerName of the person managing the eventShort Text
descriptionDetailed description of the eventLong 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:

  1. # \myclub_root\events\models.py
  2. 1 from django.db import models
  3. 2
  4. 3 class Event(models.Model):
  5. 4 name = models.CharField('Event Name', max_length=120)
  6. 5 event_date = models.DateTimeField('Event Date')
  7. 6 venue = models.CharField(max_length=120)
  8. 7 manager = models.CharField(max_length=60)
  9. 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 from django.db. If you used startapp, this line will already be in your file.
  • Line 3 is the Event class definition. Each Django model must inherit from Django’s Model 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 Django CharField. A CharField is a short line of text (up to 255 characters). Here, the max_length option sets the maximum length of the event name to 120 characters. The name 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 Django DateTimeField. A DateTimeField records a Python datetime object. The event_date field has a single argument—the verbose name for the field. Note that I have named the field event_date, rather than just date. This is to avoid confusion with Python’s date() 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 and manager are both Django CharFields. As the max_length argument is required on CharFields, max_length is set to limit the size of the field.
  • Line 8. description is a Django TextField. A TextField 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 is False; 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:

  1. python manage.py makemigrations

Hit enter and then run the command:

  1. python manage.py migrate

Your terminal output should look something like this:

  1. (env_myclub) ...\myclub_root> python manage.py makemigrations
  2. Migrations for 'events':
  3. events\migrations\0001_initial.py
  4. - Create model Event
  5. (env_myclub) ...\myclub_root> python manage.py migrate
  6. Operations to perform:
  7. Apply all migrations: events
  8. Running migrations:
  9. 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:

  1. python manage.py sqlmigrate events 0001_initial

You should get an output that looks like this (I’ve reformatted the output for clarity):

  1. BEGIN;
  2. --
  3. -- Create model Event
  4. --
  5. CREATE TABLE "events_event" (
  6. "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
  7. "name" varchar(120) NOT NULL,
  8. "event_date" datetime NOT NULL,
  9. "venue" varchar(120) NOT NULL,
  10. "manager" varchar(60) NOT NULL,
  11. "description" text NOT NULL
  12. );
  13. 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).

Your First Model - 图1

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.