Django Models and Databases: A Practical Guide Using ORM

- Andrés Cruz - ES En español

Video thumbnail

When I started with Django, what surprised me the most was its approach to managing the database through models. If you come from the PHP ecosystem—as was my case when working with frameworks like Laravel or CodeIgniter—you will notice a very interesting difference: in Django you can centralize all your table definitions within a single file per application, maintaining clean, structured, and orderly control of your data.

In this article I'll teach you what models in Django are, how to create them step by step, and how to take advantage of them to structure your database professionally with the ORM, getting to know essential field types, their relationships, the migration process, and registration in the administration panel.

We start from the previous step: if you haven't set up your first project yet, I suggest reviewing how to create our first Hello World in Django.

What a model in Django is and why it is so important

Video thumbnail

A model is one of the cornerstone pieces of the MTV (Model–Template–View) design pattern in Django.
It represents both the structure and behavior of your application's entities. In database terms, each model equals a table, and each attribute defined within the class translates into a column.

In Django, the model is your direct bridge to the database: it defines how records are stored, what constraints apply, how they relate to each other, and how you interact with them using Django's ORM (Object-Relational Mapping), without needing to write manual SQL queries.

The model within the MTV pattern

The model represents the "M" of the MTV architecture and assumes three key responsibilities:

  • Structuring data: defines column names, data types (CharField, IntegerField, TextField), and validations.
  • Managing entity relationships: establishes foreign key links (ForeignKey), one-to-one relationships (OneToOneField), or many-to-many relationships (ManyToManyField).
  • Encapsulating business logic: stores custom methods, calculated properties, and specific rules for each entity.

Models constitute the single source of truth about your data. If your platform manages pets, you will have a Dog model; if it manages a blog, you will have a Post model and a Comment model.

Database connection: the role of migrations

Once a model is defined in Python code, Django's migration system comes into play. A migration is an automatically generated file that describes the schema modifications that must be applied to the database engine to match what you defined in your models.

By default, a freshly created project in Django uses SQLite, an embedded, ready-to-use database engine whose configuration resides in the DATABASES block of the settings.py file. Later in our learning we will see how to connect robust engines in production, such as PostgreSQL or MySQL.

How Django turns a Python class into a table

When you declare a class that inherits from models.Model inside models.py and run migrations, Django inspects the attributes and internally executes the CREATE TABLE command with the precise syntax of the engine you are using. That clean and transparent abstraction is the greatest benefit of Django's ORM.

Modular structure: the models.py file

To work with models, you must first have an application created within your project. In our example we will rely on the application:

firstProject

Inside the application directory you will find the models.py file. As its name anticipates, this module serves to define all models corresponding to that application.

If you have prior experience with PHP or frameworks like Laravel, this might catch your attention at first: in Laravel, a file is usually created for each model (for example, User.php, Post.php). In Django, thanks to Python's package and module system, we can define multiple related classes within the same models.py, granting global visibility of the entire schema for that app.

Having a module's entities concentrated in its own models.py makes it easy to audit dependencies between classes, maintain consistency in relationships, and modularize data logic cleanly.

How to create a model in Django

Creating a model is as straightforward as declaring a Python class that inherits from models.Model (provided by django.db.models). Each attribute you declare in that class will be a column with its own rules and constraints in the table.

Common field types in django.db.models

Django provides an extensive repertoire of classes to model virtually any data type in your database:

  • models.CharField: for limited-length text strings (requires the max_length parameter).
  • models.TextField: for long texts, descriptions, or editorial content without a fixed limit.
  • models.IntegerField and models.PositiveSmallIntegerField: for integer numeric values or positive small integers.
  • models.FloatField and models.DecimalField: for decimal numbers or financial amounts with digit and precision control.
  • models.BooleanField: for boolean values (True or False).
  • models.DateField and models.DateTimeField: for storing dates and timestamps with support for auto_now_add and auto_now.
  • models.SlugField: for generating URL-friendly readable identifiers based on alphanumeric text and hyphens.
  • models.ForeignKey: for establishing one-to-many relationships with referential integrity.

You can check the complete and detailed list of options in the official Django Model Fields documentation.

Let's see a first practical example with a comments model:

from django.db import models

class Comment(models.Model):
    text = models.TextField()
    date_posted = models.DateTimeField(auto_now_add=True)
    element = models.ForeignKey(Element, related_name='comments', on_delete=models.CASCADE, null=True)

    def __str__(self):
        return 'Comentario #{}'.format(self.id)

Explanation of the Comment model

Let's analyze what makes up this first model:

  • text = models.TextField(): field intended to store the body of the comment without a rigid size restriction.
  • date_posted = models.DateTimeField(auto_now_add=True): stores the creation date and time. With the auto_now_add=True argument, Django automatically assigns the current server timestamp when inserting the record for the first time.
  • element = models.ForeignKey(Element, related_name='comments', on_delete=models.CASCADE, null=True): establishes a foreign relationship to the Element model. The on_delete=models.CASCADE parameter ensures that if the parent element is deleted, its associated comments are deleted in cascade; while null=True allows the field to accept null values in the database if necessary.
  • The special method def __str__(self): defines the readable text representation of the model instance, returning in this case a string like Comentario #1.

Practical case: model design in elements/models.py

To see how multiple models interact in a real project, suppose an app named elements where we model categories, content types, and general publications.

We edit the elements/models.py file with the following structure:

from django.db import models

# Create your models here.
class Category(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)

    def __str__(self):
        return self.title

class Type(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255)

    def __str__(self):
        return self.title

class Element(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(max_length=255, blank=True)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2, default=6.10)  # ej: 12345678.10
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    type = models.ForeignKey(Type, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

Step-by-step breakdown of the code:

First, we import the models module from django.db:

from django.db import models

Next, we declare each class inheriting from models.Model:

class Category(models.Model):
    # attributes and methods

class Type(models.Model):
    # attributes and methods

class Element(models.Model):
    # attributes and methods

With this inheritance, Django equips each of these classes with full ORM functionality: access to the query manager (objects), persistence methods like save() and delete(), and compatibility with migrations.

In this case, Category and Type act as master models or auxiliary catalogs, whereas Element represents the main business entity (an article, a course, or any publishable content).

Detail of the fields of the Element model

  • title = models.CharField(max_length=255): short text field. The mandatory max_length=255 argument restricts the length at the database level (generally a VARCHAR(255) column).
  • slug = models.SlugField(max_length=255, blank=True): field specialized in storing slugs suitable for friendly URLs. The blank=True modifier indicates that the field can be left empty when validating forms in the admin panel or views.
  • price = models.DecimalField(max_digits=10, decimal_places=2, default=6.10): ideal for monetary values. Requires defining max_digits (total digits supported) and decimal_places (number of decimal places). We define a default value with default=6.10.
  • category = models.ForeignKey(Category, on_delete=models.CASCADE) and type = models.ForeignKey(Type, on_delete=models.CASCADE): create many-to-one relationships with their respective models. With on_delete=models.CASCADE we ensure referential integrity in the database by deleting dependent elements when the associated category or type is deleted.
  • description = models.TextField(): rich or extensive text field, optimal for storing the body or synopsis of the content.
  • created = models.DateTimeField(auto_now_add=True) and updated = models.DateTimeField(auto_now=True): while auto_now_add=True sets the creation date once upon record insertion, auto_now=True updates the timestamp every time the save() method is called, allowing auditing of the last modification.

Migrations: synchronizing your models with the database

Having the classes declared in models.py does not automatically create the tables. To materialize them in the database, we must resort to two fundamental Django commands:

python manage.py makemigrations
python manage.py migrate

What does each one do?

  • python manage.py makemigrations: examines changes in your models within models.py and drafts migration files (located in your app's migrations/ folder).
  • python manage.py migrate: reads those pending migrations and executes the corresponding SQL instructions on the active database engine.

Recommendation: keep your migrations synchronized and committed in your Git repository. Avoid altering fields or deleting attributes without previously generating their corresponding migration with makemigrations, as you could break consistency between the code and the database.

Registration and management in the Django administration panel

One of Django's great advantages over other frameworks is its production-ready administrative panel (django.contrib.admin). To manage your new models from the visual interface, you only need to register them in your application's admin.py file:

from django.contrib import admin
from .models import Category, Type, Element

admin.site.register(Category)
admin.site.register(Type)
admin.site.register(Element)

After starting the server with python manage.py runserver and entering the /admin route with your administrator user, you will be able to create, view, modify, and delete records of Category, Type, and Element using automatically generated forms.

The magic __str__ method: text representation of a model

An indispensable detail when working with models is declaring Python's __str__() method. If you do not implement it and attempt to print an instance or see it listed in the administration panel, you will get a generic, uninformative string:

<Comment: Comment object (1)>

Where Comment is the class and (1) is its primary key (id).

By overriding __str__() in your class, you decide what information will represent the record when converted to a text string:

class Comment(models.Model):
    text = models.TextField()
    date_posted = models.DateTimeField(auto_now_add=True)
    element = models.ForeignKey(Element, related_name='comments', on_delete=models.CASCADE, null=True)

    def __str__(self):
        return f'Comentario #{self.id}'

This way, when you invoke print(comentario) or when Django lists the record in an admin selector, it will display cleanly as:

Comentario #1

Inside __str__() you have access to any attribute of the instance (such as self.title, self.id, or self.slug), which brings clarity both in the console and in the graphical interface.

⚠️ Common errors and best practices when designing models

  • Confusing null=True and blank=True: remember that null=True applies at the database level (allows NULL values in the column), whereas blank=True applies at the form validation level in Django.
  • Forgetting to implement __str__(): without this method, your lists in the administration panel and your records in the debugger will be much harder to identify.
  • Modifying a model and not migrating: every time you add, rename, or remove an attribute in models.py, you must immediately run python manage.py makemigrations and python manage.py migrate.
  • Choosing the wrong numeric type: for prices and financial amounts, always use DecimalField instead of FloatField to avoid precision issues in mathematical operations.

Conclusion

Models are the heart of every application in Django. Through them you define the data architecture, establish solid relationships, and make the most of the ORM to keep code clean, secure, and decoupled from the underlying SQL engine.

Investing time in properly structuring your models and their relationships in models.py guarantees that your project is scalable and easy to maintain as it grows in complexity.

❓ Frequently Asked Questions (FAQ)

  • What is the difference between a model and a migration in Django?
    • The model is the definition of your entity in Python code (inside models.py); the migration is the generated file that translates those changes into SQL instructions to create or modify the actual tables in the database.
  • What is Django's ORM and what advantages does it offer?
    • The ORM (Object-Relational Mapping) allows interacting with the database using Python objects and methods instead of writing SQL queries directly. This brings portability between different engines (SQLite, PostgreSQL, MySQL) and prevents SQL injections by default.
  • How to relate models to each other in Django?
    • You can use models.ForeignKey for one-to-many relationships, models.OneToOneField for one-to-one relationships, or models.ManyToManyField for many-to-many relationships.
  • Where is the models.py file defined?
    • It is located at the root of each Django application. Each application can have its own models.py with its respective entities.
  • What commands are used to apply database changes?
    • First, python manage.py makemigrations is executed to record the change in a migration file, and then python manage.py migrate to impact it in the database.
  • What is the difference between null=True and blank=True in a model field?
    • null=True indicates that the database column can store a NULL value, whereas blank=True determines whether the field is optional in form validation and in the administration panel.

The next step consists of discovering how to configure and connect a MySQL database in a Django project.

Learn what models are in Django, how to create them in `models.py`, define field types, use the ORM, and synchronize your database with migrations—step by step.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.