Model Methods & __str__ (Django)
Model methods add behavior to a Django model alongside its data. Common ones are __str__ (the object's readable name), get_absolute_url (its canonical URL), and custom methods that compute or act on the instance's data.
Django
Putting logic on the model — the 'fat models' philosophy — keeps business rules next to the data they operate on, where any view or the admin can reuse them. A method like post.is_recent() or order.total() belongs on the model, not copied into each view.
Two methods are conventional: __str__ returns a human-readable string used in the admin and shell, and get_absolute_url returns the object's URL (usually via reverse), which the admin's 'View on site' link and templates can use.
You can also override save() to add behavior when a row is written (for example auto-generating a slug), remembering to call super().save() so the actual write still happens.
Syntax
def __str__(self): return self.title
def get_absolute_url(self): return reverse(...)Examples
Python
from django.urls import reverse
from django.utils.text import slugify
class Article(models.Model):
title = models.CharField(max_length=200)
slug = models.SlugField(blank=True)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)