1

We are creating a python django model.What is the use of __str__below? What str is actually returning and where? Sample code 1

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    image = models.FileField(upload_to='profile_pics',
    blank=True,default='default.jpg')

    def __str__(self):
        return self.user.username+ " Profile"

Sample code 2

from django.db import models
from django.contrib.auth.models import User

# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
  • In `__str__()` you define how an object is printed: https://docs.python.org/3/reference/datamodel.html#object.__str__ – Klaus D. Jan 30 '21 at 06:53
  • Duplicate of [this question](https://stackoverflow.com/questions/45483417/what-is-doing-str-function-in-django). – Mubashar Javed Jan 30 '21 at 07:03
  • 1
    Does this answer your question? [What is doing \_\_str\_\_ function in Django?](https://stackoverflow.com/questions/45483417/what-is-doing-str-function-in-django) – Mubashar Javed Jan 30 '21 at 07:04

1 Answers1

1

There is use of __str__ is a string representation of that specific class

when we print an actual object of that class at that time call this method like in normal python oop concept like see following stuff

class StringRepresentation():
    pass

obj = StringRepresentation()
print(obj) # output will be "<__main__.StringRepresentation object at 0x7fa596a57890>"

# after using __str__
class StringRepresentation():

   def __str__(self):
       return "String representation of StringRepresentation class"

obj = StringRepresentation()
print(obj) # output will be "String representation of StringRepresentation class"

Here in the Django model, We define str for printing object in an understandable manner

you can also define model without str but given you the output like <QuerySet [<Profile:>,<Profile:>,<Profile:>....]

when you used it it will give the return value with class name for understand and best view for django admin side

let me know you have still query

l.b.vasoya
  • 1,188
  • 8
  • 23
  • @MayankBhatt Please mark as the right answer or upvote if you got the answer will help other people in future – l.b.vasoya Jan 30 '21 at 12:11