Django Models: What They Are, How to Create Them, and Field Types Explained Step by Step

- Andrés Cruz - ES En español

Video thumbnail

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

In this article I show you what models in Django are, how to create them step by step, and how to leverage them to structure your database professionally with the ORM, getting to know the essential field types, their relationships, the migrations process, and registration in the admin panel.

We start from the previous step: if you haven't set up your first project yet, I suggest checking out 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 cornerstones of the MTV (Model–Template–View) design pattern in Django.
It represents both the structure and the behavior of your application's entities. In database terms, each model is equivalent to a table, and each attribute defined inside 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 one another, and how you interact with them through Django's ORM (Object-Relational Mapping), without needing to write manual SQL queries.

The model within the MTV pattern

The model represents the "M" in the MTV architecture and takes on three key responsibilities:

  • Structure data: defines column names, data types (CharField, IntegerField, TextField), and validations.
  • Manage relationships between entities: establishes foreign key links (ForeignKey), one-to-one relationships (OneToOneField), or many-to-many relationships (ManyToManyField).
  • Encapsulate business logic: stores custom methods, computed properties, and rules specific to 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 migrations system comes into play. A migration is an automatically generated file that describes the schema modifications that must be applied to the database engine so they match what you defined in your models.

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

How Django turns a Python class into a table

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

Modular structure: the models.py file

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

firstProject

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

If you have prior experience with PHP or frameworks like Laravel, this may 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 inside the same models.py, which gives global visibility of the entire schema for that app.

Having a module's entities concentrated in its own models.py makes it easier to audit dependencies between classes, maintain consistency across 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 values or small positive 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 readable URL identifiers based on alphanumeric text and hyphens.
  • models.ForeignKey: for establishing one-to-many relationships with referential integrity.

You can consult the full, detailed list of options in the official Django Model Fields documentation.

Let's look at 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 comment body without a rigid size restriction.
  • date_posted = models.DateTimeField(auto_now_add=True): saves the creation date and time. With the auto_now_add=True argument, Django automatically assigns the current server timestamp when the record is first inserted.
  • 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 needed.
  • 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: designing models in elements/models.py

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

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 code breakdown:

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):
    # atributos y métodos

class Type(models.Model):
    # atributos y métodos

class Element(models.Model):
    # atributos y métodos

With this inheritance, Django gives each of these classes all the 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, while Element represents the main business entity (an article, a course, or any publishable content).

Details of the Element model fields

  • title = models.CharField(max_length=255): short text field. The required max_length=255 argument restricts 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 allowed) 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 when inserting the record, auto_now=True updates the timestamp every time the save() method is called, allowing you to audit the last modification.

Migrations: synchronizing your models with the database

Having the classes declared in models.py does not create the tables automatically. 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 inside models.py and writes migration files (located in the migrations/ folder of your app).
  • python manage.py migrate: reads those pending migrations and executes the corresponding SQL statements on the active database engine.

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

Registration and management in the Django admin panel

One of Django's great advantages over other frameworks is its production-ready admin panel (django.contrib.admin). To manage your new models from the visual interface, you just need to register them in your app'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 going to the /admin route with your admin user, you can create, view, modify, and delete records for Category, Type, and Element with automatically generated forms.

The __str__ magic method: text representation of a model

An essential detail when working with models is declaring Python's __str__() method. If you don't implement it and try to print an instance or see it listed in the admin 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 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 call print(comentario) or when Django lists the record in an admin dropdown, 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 mistakes 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 listings in the admin panel and your logs 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 Django application. Through them you define your data architecture, establish solid relationships, and make the most of the ORM to keep code clean, safe, and decoupled from the underlying SQL engine.

Investing time in properly structuring your models and their relationships in models.py ensures 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 statements 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) lets you interact with the database using Python objects and methods instead of writing SQL queries directly. This brings portability across different engines (SQLite, PostgreSQL, MySQL) and prevents SQL injections by default.
  • How do you 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 app. Each app can have its own models.py with its respective entities.
  • Which commands are used to apply database changes?
    • First you run python manage.py makemigrations to record the change in a migration file, and then python manage.py migrate to apply it to the database.
  • What is the difference between null=True and blank=True on 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 admin panel.

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

Discover how Django models work, how to define fields such as CharField, DecimalField, or ForeignKey, and how the Django ORM translates your Python classes into database tables—all without writing any SQL. Includes step-by-step examples.


Ú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.