How To Create Django Models

Introduction

In the previous tutorial, “How To Create a Django App and Connect it to a Database,” we covered how to create a MySQL database, how to create and start a Django application, and how to connect it to a MySQL database.

In this tutorial, we will create the models that define the fields and behaviors of the Blog application data that we will be storing. These models map the data from your Django application to the database. It’s what Django uses to generate the database tables via their object relational mapping (ORM) API, referred to as “models.”

Prerequisites to Create Django Models

This tutorial is part of the Django Development series and is a continuation of that series.

  • You have Django version 4 or higher installed.
  • You have connected your Django app to a database.
  • You are working with a Unix-based operating system, preferably an Ubuntu 22.04 cloud server.

Step 1 — Create Django Application

To be consistent with the Django philosophy of modularity, we will Create Django Models app within our project that contains all of the files necessary for creating the blog website.

cd ~/my_blog_app
. env/bin/activate
cd blog
python manage.py startapp blogsite

Step 2 — Add the Posts Model

Open and edit the models.py file to contain the code for generating a Post model:

from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=255)
    content = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)
    author = models.TextField()

    def get_absolute_url(self):
        return reverse('blog_post_detail', args=[self.slug])
    
    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super(Post, self).save(*args, **kwargs)

    class Meta:
        ordering = ['created_on']

        def __unicode__(self):
            return self.title

Step 3 — Update Settings

Add the blogsite app to the INSTALLED_APPS section in settings.py:

INSTALLED_APPS = [
    'blogsite',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

Step 4 — Make Migrations

Create migration files for the models:

python manage.py makemigrations

Apply the migrations to the database:

Step 5 — Verify Database Schema

Log into MySQL and verify that the tables were successfully created:

SHOW TABLES;
DESCRIBE blogsite_comment;
DESCRIBE blogsite_post;

Conclusion about Create Django Models

In this tutorial, we’ve successfully added essential models for basic functionality in a dynamic blog web application. You’ve learned how to code models effectively, understand how migrations work, and the complete process of translating Django models into structured MySQL database tables. This knowledge ensures efficient database management and provides a strong foundation for building scalable web applications.