Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

Introduction to Django Models

Django is a web development framework based on Python that uses the model-view-controller (MVC) architecture.

Oct 21, 2020 • 5 Minute Read

Introduction

Django is a web development framework based on Python. Using the model-view-controller (MVC) architecture, it provides a level of abstraction and best practices to ease development.

This guide will explore the "model" part of the MVC architecture. Models are abstractions of tables in the SQL sense. Models are the components of the MVC that define the shape of the data. In Django, models are defined using Python classes.

The guide assumes you have at least intermediate-level skills in Python and at least beginner-level in Django. An introductory guide to Django can be found here.

Django Models

Each Django model maps to a single database table, and each attribute of the model maps to a database field. Models are a subclass of Django's django.db.models.Model by default.

Since they are the source of information about the data within the Django app, Django provides a way to access the stored information for CRUD (create, retrieve, update, delete) operations. This method is referred to as queries.

Sample Model

To get a better understanding of models, below is a code snippet of a School model with four fields:

  • name
  • total_population
  • date_of_establishment
  • is_private
      from django.db import models

class School(models.Model):
    name = models.CharField(max_length=20)
    total_population = models.IntegerField(default=200)
    date_of_establishment = models.DateField()
    is_private = models.BooleanField(default=False)
    

In the example above, the School model maps to a School table within the database. The model attributes map to table columns with the same defined properties, such as data types and defaults. The models.CharField() function will generate a Varchar or String field, while the models.BooleanField() will generate a Boolean field within the database.

The functions provide much-needed abstraction from database operations, which is the objective of an MVC architecture. This makes app development with Django easier.

Being a Python class, the model can also be further empowered with functions that can further process the data within an instance of an object created from the class.

For example, consider a scenario where you need to check the total population and status of a school. If the school is private, the total population should not exceed 1,000, and if it does, a message should be returned.

      def check_population(self):
    if self.is_private and self.total_population > 1000:
        return "Private school maximum capacity is 1000"
    

Databases

Models are the components that interact with the databases. In Django, databases are defined within the settings.py file as a configuration dictionary. By default, the boilerplate code generates a connection to a simple SQLite database. Below is a sample configuration dictionary.

      DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
    

For bigger projects, Postgres is a preferred database due to its reliability and capacity to handle higher traffic. Django integrates smoothly with Postgres. Below is a sample of a connection configuration with Postgres. With Postgres, however, you need some extra work to setup the database and connect it to Django. You can learn more about that in this guide.

      DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'myproject',
        'USER': 'myprojectuser',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
    }
}
    

Since the configuration is a dictionary of dictionaries, this means that it is possible to have more than one database within a Django project. To learn more about using multiple databases, check out this guide.

Conclusion

An understanding of the model component of the Django MVC allows you to learn the intricacies of the architecture and customize it for your unique needs.

To build on this guide, read further about Django model-related concepts, including:

  1. Django Databases: How to connect to different databases and how to deal with more than one database. Consult this guide for reference.

  2. Abstract Models and Inheritance: Design your own parent model that others can inherit from. Refer to this guide.

  3. Polymorphism in Django models: Refer to this guide for a deeper dive into the topic.