0

I was watching a tutorial on django and the guy added the following line of code, however he didnt exactly explain what it does.

return '%s - %s' django

the full code line is:

def __str__(self):
    return '%s - %s' % (self.post, self.author)

and i do understand it, just not that return part. Anyone mind clearing it out for me.

1
  • You construct a string, and then you return this, this is thus the result of calling the .__str__() method. Commented Jul 1, 2021 at 16:46

1 Answer 1

1

This can be found in models sometimes. It helps during debugging - when you print this object, it will call __str__ and return that instead of some random print message like Something object at 0xsomeadress.

Print will call the __str__ function on an object to retrieve a string representation which it will later on output to stdout.

It is also useful when using the UI that Django generates, as it shows the message that is returned by __str__.

Sign up to request clarification or add additional context in comments.

2 Comments

the str method i understand, my question with the { '%s - %s' } part of the code.
That's just substitution - each %s is substituted by each variable after the %, one by one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.