Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is doing __str__ function in Django?

Tags:

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  # Create your models here.   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?

like image 961
Tornike Gomareli Avatar asked Aug 03 '17 11:08

Tornike Gomareli


People also ask

What is the use of __ str __ in Django?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model. # Create your models here. This will display the objects as something always in the admin interface.

What is the purpose of __ Str__ method?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

The difference between str() and repr() is: The str() function returns a user-friendly description of an object. The repr() method returns a developer-friendly string representation of an object.

Which method will execute if __ str __ method is not available?

If we have not defined the __str__ , then it will call the __repr__ method.


2 Answers

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 
like image 54
Yilmaz Avatar answered Nov 12 '22 01:11

Yilmaz


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.

like image 27
muditrustagii Avatar answered Nov 12 '22 01:11

muditrustagii