Content Index
- What a model in Django is and why it is so important
- Database connection: the role of migrations
- How Django turns a Python class into a table
- Modular structure: the models.py file
- How to create a model in Django
- Common field types in django.db.models
- Explanation of the Comment model
- Practical case: designing models in elements/models.py
- Details of the Element model fields
- Migrations: synchronizing your models with the database
- Registration and management in the Django admin panel
- The __str__ magic method: text representation of a model
- ⚠️ Common mistakes and best practices when designing models
- Conclusion
- ❓ Frequently Asked Questions (FAQ)
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
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
Dogmodel; if it manages a blog, you will have aPostmodel and aCommentmodel.
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.pymakes 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 themax_lengthparameter).models.TextField: for long texts, descriptions, or editorial content without a fixed limit.models.IntegerFieldandmodels.PositiveSmallIntegerField: for integer values or small positive integers.models.FloatFieldandmodels.DecimalField: for decimal numbers or financial amounts with digit and precision control.models.BooleanField: for boolean values (TrueorFalse).models.DateFieldandmodels.DateTimeField: for storing dates and timestamps with support forauto_now_addandauto_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 theauto_now_add=Trueargument, 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 theElementmodel. Theon_delete=models.CASCADEparameter ensures that, if the parent element is deleted, its associated comments are deleted in cascade; whilenull=Trueallows 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 likeComentario #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.titleStep-by-step code breakdown:
First, we import the models module from django.db:
from django.db import modelsNext, 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étodosWith 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 requiredmax_length=255argument restricts length at the database level (generally aVARCHAR(255)column).slug = models.SlugField(max_length=255, blank=True): field specialized in storing slugs suitable for friendly URLs. Theblank=Truemodifier 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 definingmax_digits(total digits allowed) anddecimal_places(number of decimal places). We define a default value withdefault=6.10.category = models.ForeignKey(Category, on_delete=models.CASCADE)andtype = models.ForeignKey(Type, on_delete=models.CASCADE): create many-to-one relationships with their respective models. Withon_delete=models.CASCADEwe 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)andupdated = models.DateTimeField(auto_now=True): whileauto_now_add=Truesets the creation date once when inserting the record,auto_now=Trueupdates the timestamp every time thesave()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 migrateWhat does each one do?
python manage.py makemigrations: examines changes in your models insidemodels.pyand writes migration files (located in themigrations/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 #1Inside __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=Trueandblank=True: remember thatnull=Trueapplies at the database level (allowsNULLvalues in the column), whereasblank=Trueapplies 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 runpython manage.py makemigrationsandpython manage.py migrate. - Choosing the wrong numeric type: for prices and financial amounts, always use
DecimalFieldinstead ofFloatFieldto 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.
- The model is the definition of your entity in Python code (inside
- 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.ForeignKeyfor one-to-many relationships,models.OneToOneFieldfor one-to-one relationships, ormodels.ManyToManyFieldfor many-to-many relationships.
- You can use
- Where is the
models.pyfile defined?- It is located at the root of each Django app. Each app can have its own
models.pywith its respective entities.
- It is located at the root of each Django app. Each app can have its own
- Which commands are used to apply database changes?
- First you run
python manage.py makemigrationsto record the change in a migration file, and thenpython manage.py migrateto apply it to the database.
- First you run
- What is the difference between
null=Trueandblank=Trueon a model field?null=Trueindicates that the database column can store aNULLvalue, whereasblank=Truedetermines 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.