Introduction
If you’re building a Django application, one of the first things you’ll need to master is models.
Models are the blueprint of your database. They define:
- What data your app stores
- How that data is structured
- Relationships between different pieces of data
In this article, we’ll break down Django models with real-life examples, so you can start building robust apps confidently.
What Is a Django Model?
A model in Django is a Python class that subclasses django.db.models.Model.
- Each class represents a database table
- Each attribute represents a column
- Django ORM handles SQL automatically
Example:
from django.db import models
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
published_date = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=100)
Here:
BlogPost→ Tabletitle,content,published_date,author→ Columns
Field Types in Django Models
Django provides many field types, some commonly used:
| Field | Description |
| ----------------- | ------------------------- |
| `CharField` | Short text |
| `TextField` | Long text |
| `IntegerField` | Integer numbers |
| `FloatField` | Decimal numbers |
| `DateTimeField` | Date & time |
| `BooleanField` | True/False |
| `ForeignKey` | Many-to-One relationship |
| `ManyToManyField` | Many-to-Many relationship |
| `OneToOneField` | One-to-One relationship |
Real-Life Example: Blog App
Suppose we are building a blog website. We need:
- User table
- BlogPost table
- Comment table
Models
from django.db import models
from django.contrib.auth.models import User
class BlogPost(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
published_date = models.DateTimeField(auto_now_add=True)
class Comment(models.Model):
post = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
author = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
Understanding Relationships
1️⃣ One-to-Many (ForeignKey)
- One user → many blog posts
- Use
ForeignKeyin the child table
author = models.ForeignKey(User, on_delete=models.CASCADE)
2️⃣ Many-to-Many (ManyToManyField)
- Example: Posts can have multiple tags
class Tag(models.Model):
name = models.CharField(max_length=50)
class BlogPost(models.Model):
title = models.CharField(max_length=200)
tags = models.ManyToManyField(Tag)
3️⃣ One-to-One (OneToOneField)
- Example: User profile for each user
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
Migrations: Sync Models to Database
After creating models:
python manage.py makemigrations
python manage.py migrate
makemigrations→ Creates migration filesmigrate→ Applies changes to the database
Django handles SQL automatically, so you don’t need to write queries manually.
Model Methods & Metadata
Adding a method
class BlogPost(models.Model):
title = models.CharField(max_length=200)
def short_title(self):
return self.title[:50]
Adding Meta options
class BlogPost(models.Model):
title = models.CharField(max_length=200)
class Meta:
ordering = ['-published_date']
ordering→ Default order when querying
Querying Models with Django ORM
# Get all posts
posts = BlogPost.objects.all()
# Get posts by a specific author
posts = BlogPost.objects.filter(author__username='john')
# Get a single post
post = BlogPost.objects.get(id=1)
# Create a post
new_post = BlogPost.objects.create(title="Django Tips", content="Learn ORM", author=user)
Django ORM makes database interactions clean, readable, and Pythonic.
Best Practices
✔ Keep models small and focused
✔ Use related_name for reverse relations
✔ Add __str__ method for easy admin readability
✔ Use choices for predefined options
Example:
class BlogPost(models.Model):
STATUS_CHOICES = [
('D', 'Draft'),
('P', 'Published')
]
status = models.CharField(max_length=1, choices=STATUS_CHOICES)
Final Thoughts
Django models are the heart of your web application.
- Define data structure
- Handle relationships
- Enable ORM queries without SQL
Once you understand models, you can build anything from blogs and e-commerce platforms to SaaS apps.