Methods __str__ and __unicode__

3

I have already seen class codes that implement Django models overriding both __str__ and __unicode__ , is there any difference between them? If so, is there a case that I should prefer one instead of another?

    
asked by anonymous 25.05.2017 / 17:31

1 answer

5
  

Is there a difference between them?

__str__() is an older form (returns bytes). __unicode__() is a new form (it returns characters, usually UTF-8).

In Django, it's a good practice to __str__() also return Unicode if you use Python 2:

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

By documentation , __unicode__() is called first. If it does not exist, __str__() is called.

  

If yes, is there any case that I should prefer one instead of another?

For Python 2, where unicode is not guaranteed transparently, __unicode__() is preferable to be used.

For Python 3, __str__() is already naturally unicode, so there is no need to have both.

    
25.05.2017 / 17:41