1

In django, why does defining __unicode__ method on some types of objects (models, etc.) result in print(obj) printing the output of __unicode__ but if I create my own classes, and define __unicode__, it doesn't seem to get called? I've read about __repr__, but it seems like all the focus in Django is on __unicode__.

What is the relationship between the two, and what is the best practice to get good string representations of my objects in my logs?

1 Answer 1

4

The Django Model class defines __str__ for you with something like this:

def __str__(self):
    return unicode(self).encode('utf-8')

Therefore, when you print(obj) (and obj is a Model), Python calls obj.__str__() which calls unicode(obj) which calls obj.__unicode__().

If you create your own class and add a definition of __str__ like the one above, then you can use __unicode__ to return a unicode representation of your object, and have that one function also control the object's str representation.

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

1 Comment

Good catch inside Django :)

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.