📄️ Defining Models
So far we have been interacting with a SQLite database directly via the standard sqlite3 module. We could do the same for other database engines such as MySQL or PostgreSQL, to give a few examples, via the pymysql and pg8000 modules. However, Django provides its own API to talk to a database, known as Django ORM. This API aims to abstract the diversity of SQL dialects into a common language using Python classes and functions. Thus, you will no longer be working with SQL code directly, unless it is a very specific query that the Django API is not able to generate, which is rare.
📄️ Setting Up a Database Engine
The database engine the Django ORM will use needs to be configured in the project's configuration file myproject/settings.py. By default, the command used in the first chapter to create the project configures an SQLite database called db.sqlite3. So, in settings.py you will find this:
📄️ Migrations
We've already told Django which database we want to use and defined a model in our models.py file. Now, we want Django to actually create a table of courses with the fields defined in the Course model. We call this a migration, that is, the process by which Django generates or modifies a table (considering that we are working with relational databases) from a model.
📄️ Working With Models
We have defined a model and applied the migrations. It remains for us to see how to use the model to add and return courses from the database. We'll do some testing using Django's interactive console, which is a regular Python shell, but with access to the modules of our application. To start the Django shell, run:
📄️ Using Models in Views
Now let's apply what we just learned to our views. Let's start with the courses() view which contained this code: