The __str__ method on models to print a text representation of the model/class

- Andrés Cruz

En español
The __str__ method on models to print a text representation of the model/class

The next thing we are going to see is a feature that allows us to represent an object as a String and that is the method called Str.

Since if we try to print from a template or using the print function an object that belongs to a model (or class in general); we will see that something like the following will appear:

Comment object (1)

Where the Comment is the name of the model and the (1) is the identifier in the database.

Now, we can represent a Django model as if it were a simple text; This is really a feature that Python offers us and not Django, which is being able to represent an object as if it were a string; therefore, when we print this object, basically the representation that we define in the Str function will appear; for example, for our model:

class Comment(models.Model):
    text = models.TextField()
    date_posted = models.DateTimeField(auto_now_add=True)
    element = models.ForeignKey(Element, related_name='comments', on_delete=models.CASCADE, NULL=True)
    def __str__(self):
        return 'Comentario #{}'.format( 

Here we can access all the attributes and methods of the model that contains said function; and this method is used internally by Python to represent said instance of a class by means of a string when printing the text.

And if we print the following object:


When making a print:

Comentario #1

The text we set earlier will appear; you can use this for A whenever you have a class and at some point you want to print it, either through the print function or from the Django template.

Andrés Cruz

Desarrollo con Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz en Udemy

Acepto recibir anuncios de interes sobre este Blog.