Model Methods & Properties
Models aren't just data containers — they can have methods and properties that encapsulate business logic. This keeps logic close to the data and follows Django's 'fat models, thin views' philosophy.
15 min•By Priygop Team•Updated 2026
Model Methods
- __str__() — String representation
- save() — Override to add custom save logic
- delete() — Override for soft-delete or cleanup
- get_absolute_url() — Canonical URL for the object
- clean() — Custom model-level validation
- @property — Computed attributes (not stored in DB)
- Custom methods for business logic
Methods Example
Methods Example
# blog/models.py
# from django.db import models
# from django.urls import reverse
# from django.utils import timezone
# class Post(models.Model):
# title = models.CharField(max_length=200)
# content = models.TextField()
# created_at = models.DateTimeField(auto_now_add=True)
# published_at = models.DateTimeField(null=True, blank=True)
# views_count = models.IntegerField(default=0)
#
# def __str__(self):
# return self.title
#
# # Canonical URL for the object
# def get_absolute_url(self):
# return reverse('blog:post-detail', args=[self.pk])
#
# # Computed property — not in database
# @property
# def is_published(self):
# return self.published_at is not None
#
# @property
# def read_time(self):
# words = len(self.content.split())
# return max(1, words // 200)
#
# # Custom method
# def publish(self):
# self.published_at = timezone.now()
# self.save()
#
# def increment_views(self):
# self.views_count += 1
# self.save(update_fields=['views_count'])
#
# # Override save for custom logic
# def save(self, *args, **kwargs):
# if not self.slug:
# from django.utils.text import slugify
# self.slug = slugify(self.title)
# super().save(*args, **kwargs)Tip
Tip
Add Meta class for ordering, indexes, and constraints. class Meta: ordering = ['-created_at'] sets default ordering.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not adding __str__ to models. Without it, admin and shell show unhelpful 'Object (1)' instead of meaningful names.
Practice Task
Note
(1) Add Meta ordering to a model. (2) Create a custom manager. (3) Add db_index to a frequently queried field.
Quick Quiz
Key Takeaways
- Models aren't just data containers — they can have methods and properties that encapsulate business logic.
- __str__() — String representation
- save() — Override to add custom save logic
- delete() — Override for soft-delete or cleanup