为什么__unicode__不起作用但是__str__呢?

Sam*_*mmy 10 string django unicode django-models python-3.x

我试图通过自己开发一个网站来打破一些摇滚,我开始创建一些注册表页面并列出数据库记录.

我遇到的问题是,__unicode__方法不会打印我的记录的用户名,而且__str__确实如此!

我知道使用__unicode__是最好的做法,但我只能打印我的对象用户名__str__.

任何人都可以解释为什么会这样吗?

我的型号:

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
Run Code Online (Sandbox Code Playgroud)

我的admin.py:

from django.contrib import admin
from registo.models import User

admin.site.register(User)
Run Code Online (Sandbox Code Playgroud)

我的__unicode__(self)输出:

User
    User object
Run Code Online (Sandbox Code Playgroud)

我的__str__(self)输出:

User
    Teste
Run Code Online (Sandbox Code Playgroud)

感谢您的提前合作!

kar*_*ikr 16

它看起来像你正在使用Python3.x,这里是相关的文档Str and Unicode methods

在Python 2中,对象模型指定__str__()__unicode__() 方法.如果存在这些方法,则它们必须分别返回str(字节)和unicode(文本).

print语句和str()内置调用,__str__()用于确定对象的人类可读表示.unicode()内置调用(__unicode__()如果存在),否则返回 __str__()并使用系统编码对结果进行解码.相反,示范基类派生自动__str__()__unicode__()通过编码为UTF-8.

在Python 3中,简单地说__str__(),它必须返回str(文本).

所以

在Python 3上,装饰器是无操作的.在Python 2上,它定义了适当的__unicode__()__str__()方法(替换__str__()了过程中的原始方法).