0
0
Djangoframework~5 mins

String representation with __str__ in Django

Choose your learning style9 modes available
Introduction

We use __str__ to show a friendly name for objects when we print them or see them in admin. It helps us understand what the object is without extra code.

When you want to see a readable name for your model objects in Django admin.
When printing model instances in the console or logs to understand what they represent.
When debugging and you want clear output instead of default object memory addresses.
When displaying model objects in templates or other parts of your app where a string is needed.
Syntax
Django
class ModelName(models.Model):
    # fields here

    def __str__(self):
        return 'string representation of the object'

The __str__ method must return a string.

This method is called automatically when you print the object or show it in admin.

Examples
This shows the book's title when you print a Book object.
Django
class Book(models.Model):
    title = models.CharField(max_length=100)

    def __str__(self):
        return self.title
This combines first and last name for a clear person name.
Django
class Person(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"
Sample Program

This model Product returns a string with its name and price. When printed, it shows a friendly description.

Django
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return f"{self.name} (${self.price})"

# Example usage:
product = Product(name='Coffee Mug', price=12.99)
print(str(product))
OutputSuccess
Important Notes

Without __str__, Django shows a less helpful default like <Product object (1)>.

Always return a string, not other types like numbers or None.

Summary

__str__ makes your model objects easy to read and understand.

It is used automatically in admin and when printing objects.

Return a clear, simple string that describes the object well.