Working with Django Models and Databases
In this article, we will explore Django models and databases in-depth. Django, a Python-based framework, adheres to the MVT (Model View Template) architectural pattern. It’s a vital tool for developers that assists in seamless web application development, where models play a crucial role. Think of models as a blueprint for your database. Understanding models and databases in Django will help you build dynamic, data-driven web applications.

Regardless of whether you’re a novice Python enthusiast or an experienced professional, this article will guide you step-by-step through practical examples and explanations.
Table of Contents
- Understanding Django Models
- Creating a Django Model
- Working with Django Databases
- Migrating Changes to the Database
- Manipulating Django Database with the ORM
- FAQs
- Conclusion
Understanding Django Models
A model in Django represents a single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Each Django model is translated into a database table in the backend.
A Django model is a Python class that subclasses django.db.models.Model
. Each attribute of the model represents a database field.
Let’s consider a blog application, where you have posts, authors, comments etc. Each of these can be represented as a model. For instance, you can define a Post model to store different posts, containing fields like title, content and date of posting.
Creating a Django Model
We start by creating a Django application. Once you do that, a file called models.py
is auto-generated within the app directory. Here’s where you define your models.
Let’s create a model for our hypothetical Blog:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
pub_date = models.DateTimeField(auto_now_add=True)
The Post
model has three fields – title
, content
, and pub_date
.
title
is a character field (CharField
) that allows you to store a string with a maximum length of 200.content
is a text field (TextField
) meant for longer text.pub_date
is a date-time field (DateTimeField
) that automatically gets set with the current date and time when a post is created.
Working with Django Databases
Django comes with an object-relational mapper (ORM) that allows you to interact with your database like you would with SQL. In other words, it’s a way to create, retrieve, update, and delete records in your database using Python code.
The settings for your database are stored in the DATABASES
dictionary in your settings file. By default, Django uses SQLite, but you can also use other databases like PostgreSQL, MySQL, or Oracle.
Here’s what the default database configuration looks like:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
Migrating Changes to the Database
Once you’ve defined a model, Django provides a built-in database abstraction API that lets you create, retrieve, update, and delete objects. But first, you need to tell Django to create a table for the Post
model in your database. You do this by running a “migration” command.
Django use the command python manage.py makemigrations
to auto-generate the SQL commands needed to create the table defined by your model. Django keeps track of these migrations and applies them sequentially to keep your models and database in sync.
To apply migrations and thus create the table in the database, use the migrate
command:
python manage.py migrate
Manipulating Django Database with the ORM
With the tables created, we can now start working with data. Django’s ORM allows us to interact with our data as if they were Python objects. Let’s create a new post:
from blog.models import Post
# Create a new Post
Post.objects.create(title='My First Post', content='This is my first post.', pub_date=timezone.now())
We can retrieve all the saved posts as below:
# Retrieve all posts
Post.objects.all()
We can also update existing posts:
# Updating a Post
post = Post.objects.get(pk=1) # Get the Post with primary key (id) of 1
post.title = 'My Updated Post'
post.save()
And, finally, to delete a post:
# Deleting a Post
post = Post.objects.get(pk=1)
post.delete()
FAQs
-
What is Django’s ORM?
Django’s ORM is a way to create, retrieve, update, and delete records in your database using Python. -
What are Django migrations?
Migrations are Django’s way of propagating changes you make to your models into your database schema. -
What is a Django model?
A Django model is a single, definitive source of information about your data. -
How do we define a Django model?
A Django model is defined as a subclass ofdjango.db.models.Model
, and its attributes represent database fields. -
What databases can Django work with?
Django can work with databases like SQLite, PostgreSQL, MySQL, or Oracle.
Conclusion
Django makes it easier for developers to create complex databases and perform CRUD operations using Python code rather than SQL commands. Mastering Django models and databases is crucial for building robust web applications, and it’s a major stepping stone in your journey as a Django developer. Keep practicing and experimenting!