0 day streak
python / beginner
Snippet

Defining Model String Representation

In Django, the __str__ method determines how a model instance is displayed in the admin interface and the shell. Without it, you would only see generic labels like 'Article object (1)'.

snippet.py
python
1
2
3
4
5
6
7
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
django
Breakdown
1
class Article(models.Model):
Defines a new database model named Article.
2
def __str__(self):
A special Python method that returns a human-readable string for the object.
3
return self.title
Returns the article's title to be used as its display name.