The Model __str__ Method
In this page:
Why __str__ Matters
Without a __str__ method, printing a model instance shows an unhelpful default like 'Book object (1)', which makes debugging and admin browsing harder.
Example: Why __str__ Matters
Without a __str__ method, printing a model instance shows an unhelpful default like 'Book object (1)', which makes debugging and admin browsing harder.
class Book(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Building a Readable String
__str__ can combine multiple fields with an f-string to produce a more descriptive label than just one field.
Example: Building a Readable String
__str__ can combine multiple fields with an f-string to produce a more descriptive label than just one field.
class Order(models.Model):
customer_name = models.CharField(max_length=100)
total = models.IntegerField()
def __str__(self):
return f'{self.customer_name} - {self.total}'
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
Seeing It in Action
Once __str__ is defined, printing an instance or looping over a QuerySet in the shell shows the readable label instead of a generic object reference.
Example: Seeing It in Action
Once __str__ is defined, printing an instance or looping over a QuerySet in the shell shows the readable label instead of a generic object reference.
book = Book.objects.get(id=1)
print(book)
⚠️ Run this command in your terminal.
- Leaving __str__ undefined, so every object shows up as an unhelpful 'Book object (1)' in the admin and shell.
- Returning a non-string value from __str__, such as an integer, which raises a TypeError.
- Making __str__ do expensive database queries, slowing down every place the object gets printed or listed, like the admin site.
- __str__ is a method that returns a human-readable string representing the object.
- Django uses __str__ to display objects in the admin site, shell, and templates.
- Without __str__, objects show up as a generic 'ModelName object (id)'.
- __str__ must return a string, built from the object's own fields.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: