为什么__unicode__不起作用__str__? [英] Why __unicode__ doesn't work but __str__ does?
问题描述
我正在通过开发一个网站来打破一些摇滚,我开始创建一些注册表页面和列出数据库记录。
I'm trying to break some rock by developing a website on my on, and i'm starting by creating some registry pages and listing database records.
我的错误是因为 __ unicode __
方法不会打印我的记录的用户名,而 __ str __
And i'm getting bugged with the fact that __unicode__
method doesn't print the username of my records and __str__
does!
我知道使用 __ unicode __
是最好的做法,但我只能打印我的对象用户名
And i know that using __unicode__
is the best practice to have, but i can only print my object username with __str__
.
任何人都可以解释为什么会这样吗?
Can anybody explain why this happens?
我的模型:
from django.db import models
class User(models.Model):
username = models.CharField(max_length=200)
reg_date = models.DateTimeField('registry date')
def __unicode__(self):
return self.username
我的admin.py:
My admin.py:
from django.contrib import admin
from registo.models import User
admin.site.register(User)
我的 __ unicode __(self)
输出:
User
User object
我的 __ str __(self)
输出:
User
Teste
感谢你的合作提前!
推荐答案
看起来你正在使用 Python3.x
这里是 <$ c上的相关文档$ c> Str和Unicode方法
it looks like you are using Python3.x
and here is the relevant documentation on Str and Unicode methods
在Python 2中,对象模型指定
__ str __()
和__ unicode __()
方法。如果存在这些方法,它们必须分别返回str(bytes)和
unicode(text)。
In Python 2, the object model specifies
__str__()
and__unicode__()
methods. If these methods exist, they must return str (bytes) and unicode (text) respectively.
打印语句和str()内置调用 __ str __()
确定
对象的人类可读表示。 unicode()内置
调用 __ unicode __()
(如果存在),否则返回
__ str __()
,并用系统编码解码结果。相反,模型基类自动从
__ unicode __()
通过编码为UTF-编码来导出 __ str __()
8,
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.
在Python 3中,只需要 __ str __()
,它必须返回str(text) p>
In Python 3, there’s simply __str__()
, which must return str (text).
所以
在Python 3中,装饰器是不做的在Python 2中,它定义了
适当的__ unicode __()
和__ str __()
方法(替换
原始__ str __()
方法)。
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).
这篇关于为什么__unicode__不起作用__str__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!