我有几个型号有用户作为外键。用户列表正在显示用户名,但我想自定义它。是否必须使用自定义模型扩展用户模型并编写自己的__str__
函数?有更简单的方法吗?
我觉得你不能用一个可调用的字段集,对吗?
最佳答案
我认为__unicode__()
方法不正确,应该使用__str__()
方法。
对于Python 2.x
,__str__()
方法将返回str(字节),而__unicode__()
方法将返回unicode(文本)。
print语句和str内置调用来确定
对象的人类可读表示。Unicode内置
如果存在,则调用__str__()
,否则返回到__unicode__()
并使用系统编码对结果进行解码。相反,模型基类自动从
通过编码到UTF-8。
read here complete
但在__str__()
中,只有__str__()
方法,没有__unicode__()
方法。
Django提供了一种简单的方法来定义Python 3.x
和__str__()
在python 2和3上工作的方法:必须定义一个
方法返回文本并应用
装饰师。
在python 3上,decorator是一个no-op。在python 2上,它定义了
适当的__unicode__()
和__str__()
方法(替换
流程中的原始__unicode__()
方法)。
以下是Django Docs的一个示例。
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class MyClass(object):
def __str__(self):
return "Instance of my class"
解决方案:用同样的方式装饰,就像上面为你的班级所做的那样,并且
在
__str__()
中,添加将添加到用户模型的方法。from django.contrib.auth.models import User
def get_name(self):
return '{} {}'.format(self.first_name, self.last_name)
User.add_to_class("__str__", get_name)
关于python - 如何在用作外键时更改Django Admin中的用户表示?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38086235/