top of page

Learn through our Blogs, Get Expert Help, Mentorship & Freelance Support!

Welcome to Colabcodes, where innovation drives technology forward. Explore the latest trends, practical programming tutorials, and in-depth insights across software development, AI, ML, NLP and more. Connect with our experienced freelancers and mentors for personalised guidance and support tailored to your needs.

blog cover_edited.jpg

Django Models in Python: A Complete Guide for Beginners

  • Writer: Samul Black
    Samul Black
  • May 27
  • 8 min read

Updated: 5 days ago

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.

django python - colabcodes

What is Django in Python?

Django is a high-level web framework for Python that promotes rapid development and clean, pragmatic design. Originally developed in 2003 by a team of web developers at the Lawrence Journal-World newspaper, Django was released as open source in 2005.

It follows the Model-View-Template (MVT) architecture and abstracts much of the hassle of building full-stack web applications.


Key Features of Django


  • Batteries-included: Comes with an admin panel, authentication system, ORM, and more.

  • Secure: Automatically handles common vulnerabilities like XSS, CSRF, and SQL injection.

  • Scalable: Used by high-traffic sites like Instagram, Pinterest, and Mozilla.

  • Modular: Encourages reusable, maintainable code through apps and packages.

  • Fast Development: Get your MVP or prototype up and running quickly.


Why Choose Django for Web Development?

Django is ideal for:


  • Beginners learning web development with Python

  • Startups needing to build MVPs quickly

  • Enterprises looking for a robust, scalable architecture

  • Teams wanting a maintainable, DRY (Don’t Repeat Yourself) codebase


Its strong community, extensive documentation, and large ecosystem of packages make Django a future-proof choice for developers.


Who Uses Django?

Django powers websites and apps used by millions of people every day. Major companies and platforms built with Django include:


  • Instagram

  • Disqus

  • The Washington Post

  • Mozilla

  • Pinterest


What is 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.title

models.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:


  1. Django generates a corresponding table in the database.

  2. It provides a Pythonic API to interact with the data.

  3. 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.title

Let’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.title
  • This 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.


How Django Uses This


  • The model tells Django how to create the database schema.

  • Django generates a SQL CREATE TABLE statement under the hood.

  • Django also creates Python APIs to query, create, and manipulate the data.


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 Post

Common 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 Type

Description

Example Usage

Common Options

CharField

For short text, like names or titles

name = models.CharField(max_length=100)

max_length, null, blank, default

TextField

For long-form text such as article content or descriptions

body = models.TextField()

null, blank

IntegerField

Stores whole numbers

age = models.IntegerField()

null, blank, default

FloatField

Stores floating-point numbers

rating = models.FloatField()

null, blank, default

DecimalField

For decimal numbers with precision (e.g., money)

price = models.DecimalField(max_digits=6, decimal_places=2)

null, blank, default

BooleanField

Stores True or False

is_active = models.BooleanField(default=True)

default, null

DateField

Stores date values

publish_date = models.DateField()

auto_now, auto_now_add, null

DateTimeField

Stores date and time

created_at = models.DateTimeField(auto_now_add=True)

auto_now, auto_now_add, null

EmailField

Validates email format

email = models.EmailField()

max_length, null, blank

URLField

Validates URL format

website = models.URLField()

max_length, null, blank

SlugField

For URL slugs (typically lowercase and hyphenated)

slug = models.SlugField(unique=True)

max_length, unique, null

ForeignKey

Many-to-one relationship

author = models.ForeignKey(User, on_delete=models.CASCADE)

on_delete, related_name, null

OneToOneField

One-to-one relationship

profile = models.OneToOneField(User, on_delete=models.CASCADE)

on_delete, related_name, null

ManyToManyField

Many-to-many relationship

tags = models.ManyToManyField(Tag)

related_name, blank


Field Options Glossary

Option

Description

null=True

Allows the field to store NULL in the database

blank=True

Allows the field to be left blank in forms

default=value

Sets a default value for the field

unique=True

Ensures that no two entries have the same value for this field

choices=[...]

Provides a list of options to choose from

on_delete=...

Defines behavior for related objects when the referenced object is deleted


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 shell

Creating 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()


Quick Tips


  • Use exit() or Ctrl+D to exit the shell.

  • Remember to import your models before using them.

  • Shell commands interact directly with your live database, so be cautious when deleting or updating.


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
		pass

Why Use Meta Options?


  • Customize database table names (useful for legacy databases or naming conventions)

  • Set default ordering of query results

  • Provide human-friendly singular and plural names for the model

  • Define permissions or unique constraints

  • Control indexes and database-level options


Common Meta Options

Meta Option

Purpose & Example

db_table

Specifies custom database table name

ordering

Default order for querysets

verbose_name

Singular human-readable name for the model

verbose_name_plural

Plural human-readable name

unique_together

Ensures combined uniqueness across multiple fields

index_together

Creates composite database indexes on multiple fields

permissions

Custom permissions beyond default add/change/delete/view

default_related_name

Default related name for reverse relations

abstract

Declares the model as abstract (won’t create a table, used for inheritance)

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:

Option

Description

CASCADE

Deletes related posts when the author is deleted

SET_NULL

Sets the author to NULL (requires null=True)

PROTECT

Prevents deletion if related objects exist


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

Relationship Type

Field Type

Example Use Case

One-to-Many

ForeignKey

Post to Author

One-to-One

OneToOneField

User to Profile

Many-to-Many

ManyToManyField

Post to Tag


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.

Commentaires


Get in touch for customized mentorship, research and freelance solutions tailored to your needs.

bottom of page