What is doing __str__ function in Django?

前端 未结 6 2419
猫巷女王i
猫巷女王i 2021-02-13 13:09

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 mo         


        
6条回答
  •  轮回少年
    2021-02-13 14:03

    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.

提交回复
热议问题