Episode 11 of 32

Model Methods

Add custom methods to your models — create a snippet method that returns a truncated version of the article body for previews.

Model Methods

Models are Python classes, so you can add custom methods to them. This is cleaner than doing string manipulation in templates or views.

Adding a Snippet Method

# articles/models.py
class Article(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField()
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    thumb = models.ImageField(default='default.png', blank=True)

    def __str__(self):
        return self.title

    def snippet(self):
        return self.body[:50] + '...'

Using Model Methods in Templates

<!-- Call the method without parentheses -->
{% for article in articles %}
    <h2>{{ article.title }}</h2>
    <p>{{ article.snippet }}</p>
{% endfor %}

In Django templates, you call model methods without parentheses — just use {{ article.snippet }} not {{ article.snippet() }}.

Why Model Methods?

ApproachWherePros
Model methodmodels.pyReusable everywhere, keeps templates clean
Template filterTemplateGood for display-only transformations
View logicviews.pyGood for complex business logic

More Method Examples

class Article(models.Model):
    # ... fields ...

    def snippet(self):
        return self.body[:50] + '...'

    def word_count(self):
        return len(self.body.split())

    def is_recent(self):
        from django.utils import timezone
        return self.date >= timezone.now() - timezone.timedelta(days=7)

Key Takeaways

  • Add methods to models for reusable data transformations
  • Call model methods in templates without parentheses
  • Model methods keep logic out of templates — cleaner separation
  • snippet() is a common pattern for article previews