🎓 What is a Django Model?
When you build a web application, you almost always need to store data — like users, posts, products, comments, etc.
This data is stored in a database (e.g., SQLite, PostgreSQL, MySQL).
Instead of writing SQL queries by hand, Django lets you use models, which are simple Python classes.
📌 A Django model is just a Python class that describes what your data looks like.
📌 Django then takes that class and creates the actual database table for you.
📄 How do you write a model?
You write models in the models.py file of your Django app.
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
published_at = models.DateTimeField(auto_now_add=True)
What does this do?
✅ Django will create a table named post.
✅ The table will have 3 columns:
title — a short text (maximum 200 characters)
body — long text
published_at — date and time when the post was created
🔨 How does Django turn models into a database table?
After you define the model:
1️⃣ Run:
python manage.py makemigrations
This tells Django to create a migration file (a plan for creating the table).
2️⃣ Run:
python manage.py migrate
This actually creates the table in the database.
🧪 Examples of Fields You Can Use
Here are some common field types:
name = models.CharField(max_length=100) # short text
description = models.TextField() # long text
Numbers
price = models.DecimalField(max_digits=6, decimal_places=2)
quantity = models.IntegerField()
Dates & Times
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
Boolean (True/False)
is_published = models.BooleanField(default=False)
Email & Slug
email = models.EmailField()
slug = models.SlugField()
🔗 How to Link Tables Together?
One-to-Many (ForeignKey)
Example: Many books → One author
class Author(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
Many-to-Many
Example: Students and Courses
class Student(models.Model):
name = models.CharField(max_length=100)
class Course(models.Model):
name = models.CharField(max_length=100)
students = models.ManyToManyField(Student)
🧂 Options You Can Add
Make a field required or optional:
name = models.CharField(max_length=100, blank=True, null=True)
Choices
Let users choose only from a set of values:
STATUS_CHOICES = [
('draft', 'Draft'),
('published', 'Published'),
]
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
Unique
Make sure no duplicates:
email = models.EmailField(unique=True)
🏗️ CRUD: How to Use the Model in Code?
Once your model and table are ready, you can use Django’s ORM (Object Relational Mapper) to interact with your data.
post = Post.objects.create(title="Hello", body="This is my first post!")
Read
all_posts = Post.objects.all()
one_post = Post.objects.get(id=1)
Update
post = Post.objects.get(id=1)
post.title = "Updated Title"
post.save()
Delete
post = Post.objects.get(id=1)
post.delete()
📐 More Advanced Examples
Automatically generate a slug
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
Abstract Base Class
You can create reusable base models:
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Post(TimeStampedModel):
title = models.CharField(max_length=100)
Custom QuerySet Manager
class PublishedManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(is_published=True)
class Article(models.Model):
title = models.CharField(max_length=100)
is_published = models.BooleanField(default=False)
objects = models.Manager() # Default manager
published = PublishedManager() # Custom manager
🤔 Why Use Django Models?
✅ They save you from writing SQL by hand.
✅ Keep all your data structure in one place.
✅ Automatically create and manage tables.
✅ Allow you to write Python instead of SQL.
🚀 Summary:
What you define What happens
Python class Table
Attributes Columns
Create .create()
Read .all(), .filter()
Update .save()
Delete .delete()
Top comments (0)