Dec 02, 2025
Andzelika D.
7min Read
Django models are the heart of data management in any Django application. They define the structure of your database and serve as the foundation for creating dynamic, data-driven applications.
With Django’s powerful object-relational mapping (ORM) system, working with models becomes seamless, enabling you to define, query, and manipulate data effortlessly.
Let’s explore how Django models and databases work together to bring your application to life.
Django models define the structure of your database tables. They are Python classes that map directly to database tables, so you can interact with your data in a convenient, high-level way.
Each model class represents a table, and each model attribute represents a field in that table.
Django’s ORM system eliminates the need to write raw SQL queries, simplifying tasks like creating, updating, and managing database records.
To create a model, you define a Python class inside the models.py file of one of your apps. Each attribute in the class represents a database field, and Django will automatically handle the underlying database structure when you run migrations.
Here’s an example of a simple model in Django:
# In your app's models.py file from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100) published_date = models.DateField() isbn = models.CharField(max_length=13, unique=True) def __str__(self): return self.title
The __str__() method ensures that when you query for a book, it will return the book’s title as a string representation.
In Django, model fields define the data type you want to store in your database. Each field type specifies how the data will be stored and validated.
Below are some of the most common field types:
name = models.CharField(max_length=100)
description = models.TextField()
age = models.IntegerField()
price = models.FloatField()
is_active = models.BooleanField(default=True)
birth_date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
tags = models.ManyToManyField(Tag)
Model relationships define how models are connected to each other. Django provides three main types of relationships:
user = models.ForeignKey(User, on_delete=models.CASCADE)
profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
tags = models.ManyToManyField(Tag)
These relationships let you create connections between models and establish links between data in your database.
Once you’ve created your model, Django needs to translate it into a database table. This is done through migrations, which are files that Django uses to apply changes to the database schema and keep track of changes in your models.
To create the migration file for your new model, run the following command:
python manage.py makemigrations
Django will analyze the changes in your models.py file and generate a migration file that describes those changes in a format that Django can apply to the database.
You’ll see output similar to this:
Migrations for 'myapp': myapp/migrations/0001_initial.py - Create model Book
After generating the migration, apply it to the database using the migrate command:
python manage.py migrate
This command will create the necessary tables in your database. Now, the Book model is represented by a corresponding Book table in your database, and you can start adding, querying, and managing data.
Django supports multiple databases, so you can choose the best one for your project. By default, Django uses SQLite, which is lightweight, easy to set up, and ideal for development and small projects.
For production environments, we recommend more robust databases like PostgreSQL, MySQL, or MariaDB due to their scalability and performance.
In this tutorial, let’s start by setting up the default SQLite database.
By default, Django is configured to use SQLite, which comes pre-installed with Python, so no additional setup is needed. Here’s how to make sure your project is set up to use SQLite:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}After confirming your database settings, you need to apply the initial migrations to set up the default tables (like users and sessions). Run the following command:
python manage.py migrate
This command will create the db.sqlite3 file in your project directory’s root and set up all the necessary tables for your application to run.
Once the migrations are complete, check that db.sqlite3 was created in your project folder. This file stores your database locally and will grow as you add more data.
Once you’ve set up the default SQLite database for development, you may need to integrate a more robust database management system (DBMS) as your project grows.
Django supports multiple DBMSs, including PostgreSQL, MySQL, MariaDB, and Oracle. Each has its own strengths and requires a specific configuration for integration with Django.
Let’s take a look at each of the options and how they differ from SQLite:
PostgreSQL
A powerful, open-source database with advanced features, such as support for complex queries, data types like JSON, and full-text search. It’s highly recommended for production Django applications due to its scalability, robustness, and feature set.
PostgreSQL is known for strictly adhering to SQL standards and is reliable for complex and large-scale applications.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '5432',
}
}MySQL and MariaDB
Both are fast and reliable relational databases widely used in web development. MySQL is known for its speed, while MariaDB, a fork of MySQL, focuses on community-driven development and is fully compatible with MySQL.
These databases are excellent for high-traffic web applications and are often favored for their performance.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # or 'django.db.backends.mariadb' for MariaDB
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost',
'PORT': '3306',
}
}Oracle and Microsoft SQL Server
These enterprise-grade databases offer significant power, especially for large-scale web applications.
However, their setup can be more complex, and they are typically used in specific enterprise environments where the business already relies on Oracle or SQL Server for other software.
With so many different databases available, how do you choose the right one? Here’s a quick, to-the-point breakdown:
In this section, we’ll walk through the process of integrating PostgreSQL with Django, as it’s one of the most commonly used databases for production applications.
sudo apt update sudo apt install postgresql postgresql-contrib
pip install psycopg2
sudo -u postgres psql
CREATE DATABASE mydatabase;
CREATE USER mydatabaseuser WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO mydatabaseuser;
q
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': 'localhost', # Use '127.0.0.1' if 'localhost' doesn't work
'PORT': '5432', # Default PostgreSQL port
}
}The actual PASSWORD and USER values should match the ones you set in Step 5.
python manage.py migrate
This command will create the required tables in your PostgreSQL database.
python manage.py runserver
Open http://127.0.0.1:8000/ in your browser. If the Django welcome page appears without errors, your database connection is working correctly.
In summary, Django makes working with databases simple and efficient. Its models let you define your database structure using Python, and migrations automatically handle database updates.
For development, SQLite is ideal, but for larger, production-ready projects, PostgreSQL, MySQL, or MariaDB offer better scalability and performance. Don’t worry; Django’s flexibility ensures your app can scale seamlessly as it grows.
Next, you can start working with Django views and templates to build dynamic content for your site.
Django models define the database structure using Python classes. Each model corresponds to a database table, and its attributes represent the table’s fields. When you run migrations, Django creates or updates the database tables based on your models.
To create a Django model, define a class in models.py that inherits from django.db.models.Model and specify the fields. Then, run python manage.py makemigrations and python manage.py migrate to update the database.
Yes, Django supports multiple databases. You can configure them in settings.py and use the using() method to specify which database a query should use.