What is doing __str__ function in Django?

前端 未结 6 2258
猫巷女王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 13:39

    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

    0 讨论(0)
  • 2021-02-13 13:48

    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.

    0 讨论(0)
  • 2021-02-13 13:50

    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

    Note: how objects are just plainly numbered

    to this

    .

    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 讨论(0)
  • 2021-02-13 13:55

    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

    0 讨论(0)
  • 2021-02-13 13:57

    You created Blog model. Once you migrate this, Django will create a table with "name" and "tagline" columns in your database. If you wanna 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, 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. 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:

    python manage.py shell
    from projectName.models import Blog
    Blog.objects.create(name="first",tagline="anything") //will create and save an instance. It is single step. Copy-paste multiple times.
    Blog.objects.all() //check out the result
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题