What is doing __str__ function in Django?

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

    ,,....]
    

    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:

     ,,....]
    

    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
    

提交回复
热议问题