[Answered ]-What __str__ is doing in the below code? The two code listed are different

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

Leave a comment