Declaring models with Django
Building web applications with Python & Django
🕑 This lesson will take about 20 minutes
What are models?
In Django, models are Python classes that define the structure of database tables and map to the data in your database. A Django model represents a single table or collection of data in the database, and each attribute of the model corresponds to a column in that table.
Each Django model defines the fields and behaviours of the data you're storing in the database. The fields correspond to database columns, and Django automatically creates a table for each model class in the database (models become database tables and fields become columns in the tables).
Django's ORM (Object Relational Mapping) automatically maps the fields of a model to columns in the corresponding database table allowing developers to interact with the database using Python objects rather than writing raw SQL queries (this means you can query, filter, and manipulate data using Python syntax).
Django models offer methods for creating, retrieving, updating, and deleting records in the database (CRUD operations) using Python code.
Django models also allow you to switch between different database backends (e.g., PostgreSQL, MySQL, SQLite) with little changes to your code.
Django models are created in the models.py file that exists in an app’s directory (eg. the myapp directory in this example project).
Creating models
Now let’s look at how to create models. In this example project, we will make a basic travel guide app that will provide information about different destinations people can visit. To get started, we will create our first model which will be called Destination. It will define the fields that will store data about different destinations in the database, by specifying object properties and their types.
Open the models.py file in your app directory (eg. in the myapp folder). It will already contain the following code by default:
from django.db import models
# Create your models here.
We will specify a couple of different fields that will store information about travel destinations - for now, we will define a Name and a Description field for each destination. The Name field will be a CharField and the Description field will be a TextField.
The CharField is a data type used to store short string values in a database
The TextField data type is used to store longer string values in a database
It’s a good idea to specify some defaults for CharField and TextField columns in a database such as:
null = False ensures that a value for a new record must be provided
blank = False ensures a value can’t be an empty string value, and
max_length specifies the maximum length of a string value)
Edit the code in the models.py file so it has the following code and then save your code:
Django supports different types of databases for storing data. If you go into your project’s settings.py file and scroll down through the code, you will notice there is a database configuration that can be edited. By default, Django uses sqlite - a lightweight SQL database that uses a local file in your project directory, so you don’t need to have a database server running. You can change your database configuration later, but for now, we’ll stick with sqlite.
Initialising the database
The next step is to run some commands in the VS Code Terminal to initialise the database. Django uses a system called Migrations that does all the hard work of creating tables, fields, etc. in a database for you and ensuring that the configuration we specify in our models matches the structure and setup of the database. It also makes it much easier if you need to change databases.
Run the following commands (note, if using Windows you might just need python instead of python3 at the start of the command):
python3 manage.py makemigrations - this command will look at the data types we’ve defined for the fields in our Destinations model and it will create the model for destinations.
python3 manage.py migrate - this command creates a new database for you. After running this command, you should notice a new db.sqlite3 file in the main directory of your Django project.
There are several different types of fields you can use for Django models. Here are some examples and their descriptions:
CharField - used for short text (blank = False, null = False, and max_length = 150 are good defaults to use)
TextField - used for long text (blank = False, null = False, and max_length = 150 are good defaults to use)
BooleanField - used for boolean values eg. True or False (default = False is a good default to use)
DateField - used for dates (auto_now_add = True will update the value with the current time when the record is created and when it is updated)
DateTimeField - used for date and time (can also use auto_now_add = True with DateTimeField)
EmailField - used for email addresses (blank = False, null = False are recommended defaults)
URLField - used for URLs (blank = False, null = False are recommended defaults)
IntegerField - used for storing whole numbers (blank = False, null = False are recommended defaults)
DecimalField - used for storing decimal numbers
SlugField - used for slug strings - a slug is a string that can only include characters, numbers, dashes, and underscores. It is the part of a URL that identifies a particular page on a website, in a human-friendly form (blank = False, null = False are recommended defaults)
ImageField - used for image uploads (null = False is a recommended default)
FileField - used for file uploads (upload_to = 'uploads/' is a recommended default)
FilePathField - used for file paths (path = '/path/to' is a recommended default)
Next lesson: Exploring SQLite databases in VS Code