38

I'm reading and trying to understand django documentation so I have a logical question.

There is my models.py file:

from django.db import models
   
class Blog(models.Model):
    name = models.CharField(max_length=255)
    tagline = models.TextField()
    
    def __str__(self):
        return self.name
    
class Author(models.Model):
    name = models.CharField(max_length=255)
    email = models.EmailField()
    
    def __str__(self):
        return self.name
    
class Post(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    body_text = models.TextField()
    pub_date = models.DateField()
    mod_date = models.DateField()
    authors = models.ManyToManyField(Author)
    n_comments = models.IntegerField()
    n_pingbacks = models.IntegerField()
    rating = models.IntegerField()
    
    def __str__(self):
        return self.headline

What is doing here each __str__ function in each class? What is the reason I need those functions in it?

7
  • 3
    Django will use the result of that function to display objects of that type for example in the admin interface.
    – Klaus D.
    Commented Aug 3, 2017 at 11:54
  • 3
    I don't know django but you can read about __str__
    – Rahul
    Commented Aug 3, 2017 at 11:55
  • 2
    Read the docs: docs.djangoproject.com/en/1.11/ref/models/instances/#str
    – jonrsharpe
    Commented Aug 3, 2017 at 11:57
  • 2
    it would display the object's headline when you pass the object to str function. ex.. post = Post(); str(post) would print the corresponding post's headline. Commented Aug 3, 2017 at 12:03
  • 1
    Thanks.But why I have -7 vote on this question ? Is it idiotic question ? Or I have asked question in incorrect way ? Commented Aug 3, 2017 at 14:49

8 Answers 8

24

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
17

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this

enter image description here

Note: how objects are just plainly numbered

to this

enter image description here.

Note: proper object names here

You could choose what to show in the admin panel, as per your choice. Be it a field value or a default value or something else.

0
8

This overrides the default name of the objects of this class, it's something like Author:object which isn't very helpful.

overriding it gives a more human friendly name of the object like the Author.name

4

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised. Will see step by step.Suppose below is our code.

class topics():
    def __init__(self,topics):
        print "inside init"
        self.topics=topics
my_top = topics("News")
print(my_top)

Output:

inside init
<__main__.topics instance at 0x0000000006483AC8>

So while printing we got reference to the object. Now consider below code.

class topics():
    def __init__(self,topics):
        print "inside init"
        self.topics=topics

    def __str__(self):
        print "Inside __str__"
        return "My topics is " + self.topics
my_top = topics("News")
print(my_top)

Output:

inside init
Inside __str__
My topics is News

So, here instead of object we are printing the object. As we can see we can customize the output as well. Now, whats the importance of it in a django models.py file?

When we use it in models.py file, go to admin interface, it creates object as "News", otherwise entry will be shown as main.topics instance at 0x0000000006483AC8 which won't look that much user friendly.

enter image description here

2

The __str__ function is used add a string representation of a model's object, so that is

to tell Python what to do when we convert a model instance into a string.

And if you dont mention it then it will take it by default the USERNAME_FIELD for that purpose.

So in above example it will convert Blog and Author model's object to their associated name field and the objects of Post model to their associated headline field

2

Django has __str__ implementations everywhere to print a default string representation of its objects. Django's default __str__ methods are usually not very helpful. They would return something like Author object (1). But that's ok because you don't actually need to declare that method everywhere but only in the classes you need a good string representation. So, if you need a good string representation of Author but not Blog, you can extend the method in Author only:

class Author(models.Model):
    name = models.CharField(max_length=100)
    ...

    def __str__(self):
        return f'{self.name}'  # This always returns string even if self.name is None

class Post(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    text = models.CharField(max_length=100)

author = Author.objects.create(name='David')
print(author)  # David

post = Post.objects.create(author=author, text='some text')
print(post)  # Post object(1)

Now, beyond Django, __str__ methods are very useful in general in Python. More info here.

2

For example, you define __str__() in Person model as shown below:

# "models.py"

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    
    def __str__(self): # Here
        return self.first_name + " " + self.last_name

Then, you define Person admin as shown below:

# "admin.py"

from django.contrib import admin
from .models import Person

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    pass

Now, the full name is displayed in the message and list in "Change List" page:

enter image description here

And in "Change" page:

enter image description here

And in "Delete" page:

enter image description here

Next, if you don't define __str__() in Person model as shown below:

# "models.py"

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    
    # def __str__(self): # Here
    #     return self.first_name + " " + self.last_name

Now, the object name and id are displayed in the message and list in "Change List" page:

enter image description here

And in "Change" page:

enter image description here

And in "Delete" page:

enter image description here

0

When you want to return the objects in that class then you'll see something such as <QuerySet [object(1)]>. However no body wants to see something like this. they want actual name that human can understand what exactly is present in that table, so they use this function.

Not the answer you're looking for? Browse other questions tagged or ask your own question.