What is doing __str__ function in Django? [duplicate]

You created a Blog model. Once you migrate this, Django will create a table with “name” and “tagline” columns in your database.

If you want to interact with the database with the model, for example create an instance of the model and save it or retrieve the model from db,

def __str__(self):
    return self.name 

will come handy. Open the python interactive shell in your project’s root folder via:

python manage.py shell

Then

from projectName.models import Blog 
Blog.objects.all() # will get you all the objects in "Blog" table

Also, when you look at the models in your admin panel, you will see your objects listed, with the name property.

The problem is, the return will look like this if you did not add that function:

<QuerySet [<Blog:>,<Blog:>,<Blog:>....]

So you will not know what those objects are. A better way to recognize those objects is retrieving them by one of its properties which you set it as name. This way you will get the result as follow:

 <QuerySet [<Blog:itsName>,<Blog:itsName>,<Blog:itsName>....]

If you want to test this out, run python manage.py shell and run:

from projectName.models import Blog

# The below will create and save an instance.
# It is a single step. Copy-paste multiple times.
Blog.objects.create(name="first",tagline="anything")
Blog.objects.all() # check out the result

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)