Skip to main content

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.

The main concept of this API is the model. Models represent tables from a (relational) database, but you define them directly in a Python file. Django is then responsible for executing the proper queries according to the configured database engine.

Defining models is very similar to the way we defined forms in the previous chapter. We are going to define a Course model with two fields: name (string) and enrolled_students (integer). To do this, open the myapp/models.py file and write:

from django.db import models


class Course(models.Model):
name = models.CharField(max_length=128)
enrolled_students = models.IntegerField()

models.CharField and models.IntegerField are data types of the Django ORM (not to be confused with forms.CharField and forms.IntegerField), which will then be translated into data types of the configured database engine (which can even be NoSQL databases, like MongoDB.) Since in this tutorial we are going to work with SQLite and MySQL, the Course model will represent a table in the database with two columns: name and enrolled_students.