Django Models in Python: A Complete Guide for Beginners
- Samul Black

- May 27
- 9 min read
Updated: Aug 18
In the world of web development, efficiency, scalability, and security are crucial. Enter Django, a Python-based web framework that has become one of the most trusted tools for developers around the globe. Whether you're building a simple website or a complex web application, Django empowers you to move quickly while following best practices.
This introduction will walk you through the basics of Django, why it's popular, and what makes it an excellent choice for modern web development.

What is Django in Python?
Django is a powerful, high-level web framework written in Python that enables developers to build secure, scalable, and maintainable web applications quickly. Created in 2003 by developers at the Lawrence Journal-World newspaper and released as open source in 2005, Django was designed to take the hassle out of web development—so you can focus on building your app instead of reinventing the wheel.
It follows the Model-View-Template (MVT) architecture, which promotes separation of concerns and helps streamline development. With built-in features like URL routing, database migrations, and templating, Django reduces the amount of code developers need to write and maintain.
Django comes with a rich set of features that make it a go-to framework for both small startups and large-scale enterprise applications:
Batteries-Included: Offers an admin interface, authentication system, ORM (Object-Relational Mapper), and more—right out of the box.
Secure by Default: Protects against common vulnerabilities like SQL injection, XSS, CSRF, and clickjacking.
Highly Scalable: Powers some of the world’s largest websites including Instagram, Pinterest, and Mozilla.
Modular and Reusable: Encourages clean, maintainable code through its modular app structure and reusable components.
Rapid Development: Ideal for prototyping and building MVPs (Minimum Viable Products) quickly and efficiently.
Why Choose Django for Web Development?
Django is an excellent choice for a wide range of developers and organizations, including:
Beginners learning Python and web development
Startups looking to launch MVPs in record time
Enterprises seeking a secure, scalable, and well-supported architecture
Teams that value clean, DRY (Don’t Repeat Yourself) code and long-term maintainability
With its strong developer community, vast plugin ecosystem, and extensive official documentation, Django remains one of the most reliable frameworks in modern web development.
Who Uses Django?
Django is trusted by some of the world’s most recognized brands and high-traffic platforms. Real-world examples of companies using Django include:
Instagram – Social media giant
Disqus – Popular commenting system
The Washington Post – Major news outlet
Mozilla – Makers of the Firefox browser
Pinterest – Visual discovery and bookmarking platform
Whether you're building a personal blog, a SaaS application, or a global-scale web platform, Django gives you the tools to do it quickly and correctly.
What are Django Models in Python?
In Django, a Model is a core component of the framework's Model-View-Template (MVT) architecture. It acts as the blueprint for your database, defining the structure of your data and the behaviors associated with it.
Put simply:
A Django model is a Python class that maps to a single table in your database.
Each attribute in the class represents a field in the database table. Django models not only define what data is stored, but also provide methods to query and manipulate that data—without writing raw SQL.
Why Are Models Important?
Models are central to Django because they:
Define what data your app handles (e.g., blog posts, users, products)
Determine how that data is stored in the database
Automatically create and manage database schema via migrations
Provide an intuitive Python API to query the database
Django ORM: The Power Behind Models
Django comes with a built-in Object-Relational Mapper (ORM) that translates Python code into SQL queries behind the scenes. With the ORM, you can:
Create, read, update, and delete records using Python
Define relationships (e.g., one-to-many, many-to-many) between models
Avoid writing raw SQL for most use-cases
Example: A Simple Django Model
Here’s what a basic model looks like in Django:
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.titlemodels.Model: Every model class must inherit from this base class.
CharField, TextField, DateTimeField: Field types that define the structure of your database.
str: A special method to return a readable name for each object.
What Happens Behind the Scenes?
When you define a model:
Django generates a corresponding table in the database.
It provides a Pythonic API to interact with the data.
You use commands like makemigrations and migrate to sync your models with the actual database.
Basic Anatomy of Django Models in Python
At its core, a Django model is a Python class that inherits from models.Model. Each attribute of the class represents a field in the corresponding database table.
Let’s break down the structure and key components of a typical Django model.
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=255)
content = models.TextField()
author = models.CharField(max_length=100)
published_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.titleLet’s dissect each part of the model:
1. Class Declaration
class Post(models.Model):Post: The name of the model (i.e., the table name will be appname_post by default).
models.Model: This tells Django the class is a model and should be treated as a database table.
2. Field Definitions
Each class attribute becomes a column in the database.
title = models.CharField(max_length=255)CharField: Used for short strings.
max_length: Required for CharField; defines the max number of characters.
content = models.TextField()TextField: Used for large text bodies like blog content.
author = models.CharField(max_length=100)Another short string field to store the author's name.
published_at = models.DateTimeField(auto_now_add=True)DateTimeField: Stores date and time.
auto_now_add=True: Automatically sets the field to now when the object is created.
3. String Representation
def str(self): return self.titleThis method defines how the object is represented as a string (especially useful in the admin panel and the shell).
In this case, it will show the title of the post.
In the Django shell, once the model is migrated:
>>> from blog.models import Post
>>> post = Post(title="First Post", content="Hello, world!", author="Admin")
>>> post.save()
>>> print(post.title)
First PostCommon Field Types in Django
Django offers a variety of field types to define the structure of your database tables. Here’s a reference table that outlines the most commonly used fields:
Field Options Glossary
Interacting with Django Models in the Shell
Django’s shell provides a powerful interactive environment to work directly with your models using Python code. This is incredibly useful for testing, debugging, and managing your database without building a user interface.
To start the Django shell, run this command in your project directory:
python manage.py shellCreating Records
You can create new entries (rows) in your database by instantiating a model and calling .save().
from blog.models import Post
# Create a new post object
post = Post(title="My First Post", content="Welcome to my blog!", author="Admin")
# Save it to the database
post.save()Alternatively, you can use the .create() method to do both in one step:
post = Post.objects.create(title="Another Post", content="More content here", author="Admin")Querying Records
Django's ORM lets you retrieve data easily.
Get all records:
posts = Post.objects.all() for post in posts: print(post.title)Get a single record by primary key (usually id):
post = Post.objects.get(id=1) print(post.title)Filter records based on conditions:
published_posts = Post.objects.filter(is_published=True)Get the first record matching a query:
latest_post = Post.objects.filter(author="Admin").first()Updating Records
To update a record, fetch it, modify fields, and then save:
post = Post.objects.get(id=1) post.title = "Updated Title" post.save()You can also update multiple records at once using .update():
Post.objects.filter(author="Admin").update(is_published=True)Deleting Records
To delete a single record:
post = Post.objects.get(id=1) post.delete()To delete multiple records:
Post.objects.filter(is_published=False).delete()This hands-on approach will give you great control over your data and speed up your development workflow.
Using Meta Options in Django Models
In Django, Meta options allow you to customize the behavior of your models beyond just defining fields. They provide metadata to control aspects like database table names, ordering, verbose names, and more.
Meta options are set inside an inner class called Meta within your model.
What is the Meta Class?
The Meta class is a special class inside your model where you specify configuration options that affect the model’s behavior at the database and admin level, without changing the fields or business logic.
class MyModel(models.Model):
# field definitions
class Meta:
# meta options here pass
passWhy Use Meta Options?
Django’s Meta class inside a model allows you to fine-tune how the model behaves and interacts with the database. One common use is to customize database table names, which is especially helpful when working with legacy databases or adhering to specific naming conventions. You can also set the default ordering of query results, ensuring consistent results across views without manually sorting each time. Additionally, Meta lets you define human-friendly names for your models—both singular and plural—making admin interfaces clearer. It’s also essential for specifying model-level permissions, unique constraints, and custom indexes, giving you more control over how your data is stored and accessed at the database level.
Common Meta Options
Example meta class
class Article(models.Model):
title = models.CharField(max_length=200)
published_at = models.DateTimeField()
class Meta:
db_table = 'blog_articles' # Custom table name
ordering = ['-published_at'] # Newest articles first
verbose_name = "Blog Article"
verbose_name_plural = "Blog Articles"Defining Relationships Between Models in Django
In Django, models often don’t exist in isolation. Instead, they are connected through relationships, which reflect how real-world entities are linked—like a blog post having an author or a product having many reviews.
Django provides three main types of relationships between models:
One-to-Many (ForeignKey)
One-to-One (OneToOneField)
Many-to-Many (ManyToManyField)
Let’s explore each type with examples and best practices.
1. One-to-Many Relationship (ForeignKey)
A one-to-many relationship means that one object of a model can be related to multiple objects of another model.
Use Case: A blog post has one author, but an author can write many posts.
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(Author, on_delete=models.CASCADE)on_delete Options:
2. One-to-One Relationship (OneToOneField)
A one-to-one relationship means that one object of a model relates to exactly one object of another model.
Use Case: Each user has one profile.
from django.contrib.auth.models import User
from django.db import models
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()Ensures that each user is linked to only one profile.
Commonly used to extend the built-in User model.
3. Many-to-Many Relationship (ManyToManyField)
A many-to-many relationship means that multiple objects of one model can relate to multiple objects of another model.
Use Case: A post can have many tags, and each tag can belong to many posts.
class Tag(models.Model):
name = models.CharField(max_length=50)
class Post(models.Model):
title = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag)Django automatically creates an intermediate table to manage the many-to-many relationship.
Summary Table
Conclusion
Django models are the backbone of any Django application. They provide a powerful and elegant way to define your data structure and interact with your database through Django’s robust Object-Relational Mapper (ORM). In this tutorial, we’ve covered everything from the basics to advanced usage:
What Django Models Are and how they translate to database tables
How to Define Fields using built-in field types
Creating, Reading, Updating, and Deleting Records through the Django shell
Customizing Model Behavior using the Meta class
Establishing Relationships using ForeignKey, OneToOneField, and ManyToManyField
By mastering models, you lay a strong foundation for building scalable, maintainable, and efficient web applications with Django. Whether you're crafting a blog, an e-commerce platform, or a custom dashboard, models will always be at the core of your application’s logic and data integrity.




