What is doing __str__ function in Django?

发布时间 2023-05-25 17:03:23作者: Oops!#

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