Why __unicode__ doesn't work but __str__ does?

前端 未结 2 1449
心在旅途
心在旅途 2021-02-13 19:05

I\'m trying to break some rock by developing a website on my own, and I\'m starting by creating some registry pages and listing database records.

I\'m getting bugged wit

2条回答
  •  借酒劲吻你
    2021-02-13 19:59

    it looks like you are using Python3.x and here is the relevant documentation on Str and Unicode methods

    In Python 2, the object model specifies __str__() and __unicode__() methods. If these methods exist, they must return str (bytes) and unicode (text) respectively.

    The print statement and the str() built-in call __str__() to determine the human-readable representation of an object. The unicode() built-in calls __unicode__() if it exists, and otherwise falls back to __str__() and decodes the result with the system encoding. Conversely, the Model base class automatically derives __str__() from __unicode__() by encoding to UTF-8.

    In Python 3, there’s simply __str__(), which must return str (text).

    So

    On Python 3, the decorator is a no-op. On Python 2, it defines appropriate __unicode__() and __str__() methods (replacing the original __str__() method in the process).

提交回复
热议问题