1. Models Basics — Django 3 Series for Beginners in 2021

Video Tutorial

Code on Github

In this series, we will go through the different parts of the Django framework, unlike other series. This won’t be about building any project specifically. This will just be about improving your understanding of the Django framework. This will be on top of the other project tutorials. Those will still be posted about once a week. In this first tutorial we will go over the basics of Django models and the different options available to us.

What are Django Models?

Django models are a way to create different object in the database, usually a model class maps to a table in the database and each field in the class maps to a column in that table. This allows us to easily and quickly build the database for our app without having to write any SQL. Let’s start by creating our first model.

Note — This starting code will be available in the link at the top on github, there is some code already written to allow this tutorial to solely focus on the models.

Creating a Django Model

To create a Django model we need to inherit from django.db.models.Model. If you are not familiar with object oriented programming or inheritance, what we need to do is create a subclass that has all of the functionality in the Model class. This handles all of the logic about creating the tables and columns in the database so all we need to do is define our fields. So to do this we need to create a class and pass in the models.Model class in parenthesis after the name. It should look something like this:

Next we need to define our fields.

Django Model Fields

To create a field all we need to do is create a variable and use any of the built in model fields. There’s a lot of them. Go here to see them all. Let’s go through some of the main ones here:

IntegerField — This allows us to store an integer value, there are also a BigIntergerField and a SmallIntegerField if you need something more specific with the size of number you want to hold but in most cases the IntegerField will be sufficient for what you need.

BooleanField — This will allow us to store a True/False value. This works well for checkboxes in your HTML form. There is also a NullBooleanField if you want the ability to store a null value as well.

CharField — This is a field that will let you store a character string. The max_length option is required on this. This works well for short text, for longer text you should use the TextField type.

TextField — This is a field for longer text input.

DateField/DateTimeField/TimeField — These fields store exactly what their name suggests. You can store a date only, a datetime, or only a time depending on what you need. These fields have some special optional options that are very useful that we will get into later.

EmailField — This field stores an email. It is useful when using forms because it will validate the email for you.

FloatField — This field stores a floating point number. If you need a more exact number than what an integer field provides, use this.

ImageField — This will store an image in the database, Pillow is required for this. You can install that with pip install Pillow.

FileField — This is similar to the ImageField but just a more broader type to store any file.

SlugField — Slug is a newspaper term used to define a string containing only letters, numbers, underscores, or hyphens. These are generally used in URLs. It has it’s own validation built in as well.

There are also various options you can pass into the model fields, some which are required.

Django Model Field Options

max_length — We already mentioned this one, this is required on CharField and can be used on other text based model types. This is max number of characters allowed for this field. If you are familiar with SQL this determines the size of the VARCHAR being created in the database.

null — If True, Django will be able to store a null value

blank — If True, Django will allow the form to be submitted with this field being blank

choices — This will restrict the available choices to whatever is entered here, it should be given in a sequence of 2-tuples. The default form widget will be changed to a select widget from the standard text field. (See example below)

default — Allows a default value to be specified if one isn’t entered by the user

help_text — Custom help text to show up on the form

primary_key — By default, Django will create a primary key field for you. If you want to override this you can create your own field and set primary_key=True on that field (See comment in the example below).

unique — Prevents duplicates from being saved in the database. This is very useful for fields like emails where you wouldn’t want two users to sign up with the same email.

auto_now_add — This will fill a date/datetime/time field automatically. This will set this field to the current date/time when it was added to the database, it won’t change again after that. This is useful for saving when an object was originally created.

auto_now — This field will fill the date/datetime/time field with the current date/time every time it is updated. This is useful for storing a last modified value.

Here is an example of a completed model:

Migrating Changes

The last step after creating a model is to migrate the changes to the database, to do this Django creates a migrations file and then makes those changes to the database. We will take a deep dive into migrations later but for now, all you will need to know is you need to run two commands:

The first command makes the migrations folder and the second actually makes the changes.

This is where we will stop today, there is more advanced concepts we will go into with models next including relationship fields and more ways to customize our models.