Introduction
So far, you’ve used Django models mainly to define database structure. But models can do much more than just store data — they can also contain logic.
Django allows you to add:
- methods → functions inside your model
- properties → computed attributes (like virtual fields)
This makes your models smarter, cleaner, and easier to maintain.
Instead of spreading logic across views and templates, you can centralize it inside your models — which is a best practice in Django.
What You Will Learn
By the end of this tutorial, you will understand:
- what model methods are
- what model properties are
- how to define custom methods
- how to use
@property - how to use model methods in templates
- how to organize business logic inside models
- best practices for clean Django code
Prerequisites
You should already know:
- Django models
- QuerySets and ORM
- relationships (
ForeignKey, etc.) - basic templates
1. What Are Model Methods?
A model method is simply a Python function defined inside a Django model.
It allows you to:
- add behavior to your model
- compute values
- encapsulate business logic
- keep views and templates clean
2. Basic Example of a Model Method
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
def short_content(self):
return self.content[:50]Usage in Python
post = Post.objects.first()
print(post.short_content())Usage in Template
<p>{{ post.short_content }}</p>👉 In templates, you don’t need parentheses.
3. The Special __str__() Method
You already used this, but it’s actually a model method.
def __str__(self):
return self.titleIt defines how the object appears:
- in Django admin
- in shell
- in debugging
Always include a meaningful __str__() method.
4. Model Methods with Logic
Model methods can contain real logic.
Example
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.FloatField()
discount = models.FloatField(default=0)
def final_price(self):
return self.price - (self.price * self.discount / 100)Usage
product.final_price()Template
<p>Price: {{ product.final_price }}</p>5. What Are Model Properties?
A property is a method that behaves like an attribute.
You define it using the @property decorator.
6. Example of @property
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.FloatField()
discount = models.FloatField(default=0)
@property
def final_price(self):
return self.price - (self.price * self.discount / 100)Usage
product.final_price # no parenthesesTemplate
<p>{{ product.final_price }}</p>7. Method vs Property
| Feature | Method | Property |
|---|---|---|
| Syntax | obj.method() | obj.property |
| Use case | action / logic | computed value |
| Template usage | no parentheses | no parentheses |
👉 Rule of thumb:
- use methods when action is involved
- use properties for calculated values
8. Real Example: Blog Model
from django.db import models
from django.utils.text import slugify
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def get_summary(self):
return self.content[:100]
@property
def is_long(self):
return len(self.content) > 500
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super().save(*args, **kwargs)Usage
post.get_summary()
post.is_long9. Using Model Methods in Templates
Django templates allow you to use model methods directly.
<h2>{{ post.title }}</h2>
<p>{{ post.get_summary }}</p>
{% if post.is_long %}
<p>This is a long article</p>
{% endif %}10. Model Methods with Relationships
Model methods become even more powerful when used with relationships.
Example
class Category(models.Model):
name = models.CharField(max_length=100)
def post_count(self):
return self.posts.count()👉 assuming:
related_name='posts'Usage
category.post_count()Template
<p>Posts: {{ category.post_count }}</p>11. Computed Fields Example
class Order(models.Model):
total_price = models.FloatField()
tax = models.FloatField()
@property
def final_price(self):
return self.total_price + self.tax12. Boolean Properties
Very useful in templates.
class Post(models.Model):
content = models.TextField()
@property
def is_empty(self):
return len(self.content.strip()) == 0Template
{% if post.is_empty %}
<p>No content</p>
{% endif %}13. Formatting Methods
You can format values easily.
class Product(models.Model):
price = models.FloatField()
def formatted_price(self):
return f"${self.price:.2f}"14. Using get_absolute_url()
Very important built-in convention.
from django.urls import reverse
class Post(models.Model):
slug = models.SlugField()
def get_absolute_url(self):
return reverse('post_detail', kwargs={'slug': self.slug})Why it’s useful
- used by Django admin
- used by generic views
- helps with redirects
15. Overriding save() Method
You can customize saving behavior.
Example
from django.utils.text import slugify
class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)16. When to Use Model Methods
Use model methods when:
- logic belongs to the data
- you want reusable code
- you want to keep views clean
- you want better code organization
17. When NOT to Use Model Methods
Avoid putting:
- heavy business workflows
- external API calls
- complex multi-model operations
For those, use:
- services
- utility functions
- separate modules
18. Best Practices
- keep methods simple and clear
- use
@propertyfor computed values - always define
__str__() - avoid duplicating logic in views
- keep models readable
- use meaningful method names
19. Common Mistakes
Forgetting @property
def final_price(self):Then using:
product.final_price⚠️ This will not work as expected.
Writing too much logic in models
Models should not become too complex.
Using methods incorrectly in templates
{{ product.final_price() }} ❌Correct:
{{ product.final_price }} ✔️20. Mini Project Example
E-commerce Product Model
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.FloatField()
discount = models.FloatField(default=0)
stock = models.IntegerField()
@property
def final_price(self):
return self.price - (self.price * self.discount / 100)
@property
def in_stock(self):
return self.stock > 0
def short_name(self):
return self.name[:20]Template Example
<h2>{{ product.short_name }}</h2>
<p>Price: {{ product.final_price }}</p>
{% if product.in_stock %}
<span>Available</span>
{% else %}
<span>Out of stock</span>
{% endif %}
21. Summary
In this tutorial, you learned:
- model methods add behavior to models
- properties create computed attributes
@propertysimplifies access__str__()defines representationget_absolute_url()helps with routing- overriding
save()customizes behavior - logic should live inside models when appropriate
Using model methods and properties makes your Django applications cleaner, more organized, and easier to maintain.
22. Mini Quiz
1. What is a model method?
A. A database field
B. A Python function inside a model
C. A template tag
D. A URL
2. What does @property do?
A. Creates a database field
B. Converts a method into an attribute
C. Deletes a field
D. Creates a query
3. How do you access a property?
A. obj.property()
B. obj.property
C. property(obj)
D. obj.get_property()
4. Which method defines how an object is displayed?
A. display()
B. __str__()
C. show()
D. toString()
5. What is get_absolute_url() used for?
A. Styling templates
B. Database queries
C. Returning a URL for an object
D. Authentication
23. What Comes Next?
Next tutorial:
Tutorial: Django Slugs and Clean URLs
You will learn how to create SEO-friendly URLs and improve your application’s structure.
💬 Comments
No comments yet. Be the first to comment!
Login to comment.