OceanWP

Django Models

Estimated reading: 2 minutes

One of the key features of Django is its Object-Relational Mapping (ORM) system, which allows developers to interact with their database as they would with SQL. In this tutorial, we will learn about Django models and how to create, migrate, and use them in a Django application.

What is a Django Model?

A Django model is a Python class that defines the fields and behaviors of a specific database table. A model represents a single database table and defines the fields and their types, as well as any additional properties such as constraints or relationships to other tables.

Creating a Simple Django Model

To create a model, we need to define a Python class that inherits from django.db.models.Model and define the fields of the model as class variables.

Here is an example of a simple model called “Member” that has fields for first name, last name, and date of birth:


from django.db import models

class Member(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    dob = models.DateField()

In this example, we are using three different field types: CharField, for string values, and DateField for date and time values. We can also add constraints to the fields such as max_length, null and blank.

Migrating a Django Model

Once we have defined our models, we need to create the corresponding database tables. This process is called “migrating” the models. To migrate a model, we need to use Django’s command-line utility, manage.py.

To create a migration file, we will use the command:


python manage.py makemigrations

This command will create a migration file in the app’s migrations folder, containing the instructions to create the database tables.

To apply the migration and create the tables in the database, we will use the command:


python manage.py migrate

This command will create the corresponding tables in the database.

With these simple steps, we have created a Django model, migrated it, and created the corresponding table in the database. With this basic understanding of Django models, you can start building your own models and interacting with your database in a more object-oriented way.

Share this tutorial