python 在 Django 中使用 unicode
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1818224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use of unicode in Django
提问by Hulk
Why is a unicode function required in models.py?
为什么在models.py 中需要unicode 函数?
i.e,
IE,
def __unicode__(self)
return sumid;
回答by Dominic Rodger
It's not. If you define a __unicode__()
method, Django will call it when it needs to render an object in a context where a string representation is needed (e.g. in the model's admin pages).
不是。如果您定义了一个__unicode__()
方法,Django 将在需要在需要字符串表示的上下文中(例如在模型的管理页面中)呈现对象时调用它。
The documentationsays:
该文件说:
The
__unicode__()
method is called whenever you callunicode()
on an object. Since Django's database backends will return Unicode strings in your model's attributes, you would normally want to write a__unicode__()
method for your model.
__unicode__()
每当您调用unicode()
对象时都会调用该方法。由于 Django 的数据库后端将在模型的属性中返回 Unicode 字符串,因此您通常希望__unicode__()
为模型编写一个方法。
回答by SapphireSun
I'm a bit new to Django, but I think I can help you.
我对 Django 有点陌生,但我想我可以帮助你。
First, it isn't exactly required, but it's a really good idea. The field is used to create representations of your objects in the Django admin (otherwise they all have the same name :-P) and when you print out an object to your terminal window to see what's going on (otherwise you get a generic mostly useless message).
首先,它并不是完全必需的,但它确实是一个好主意。该字段用于在 Django 管理中创建对象的表示(否则它们都具有相同的名称 :-P),并且当您将对象打印到终端窗口以查看发生了什么时(否则您会得到一个几乎无用的泛型信息)。
Second, from what you wrote, it looks like you're new to Python. I recommend reading some Python tutorials on class syntax. Also, semicolons aren't necessary in this language. The correct syntax for creating the unicode method is:
其次,从你写的内容来看,你似乎是 Python 的新手。我建议阅读一些关于类语法的 Python 教程。此外,在这种语言中不需要分号。创建 unicode 方法的正确语法是:
class Foo(models.Model):
# Model fields go here
def __unicode__(self):
return u"%i" % self.sumid
The __unicode__
method has double underscores because it is a special function, namely when the builtin function unicode( obj )
is called on it, it returns a unicode string representation of that object (sort of like java's ToString
).
该__unicode__
方法有双下划线,因为它是一个特殊函数,即当对其unicode( obj )
调用内置函数时,它返回该对象的 unicode 字符串表示形式(有点像 java 的ToString
)。
I hope this helps :-)
我希望这有帮助 :-)
回答by disklosr
I think the others have given some detailed explanations that should be more than enough for you. But here's a straightforward answer: __unicode__()
is equivalent to toString()
in Java (and many other languages)
我想其他人已经给出了一些详细的解释,对你来说应该绰绰有余。但这里有一个直截了当的答案:__unicode__()
相当于toString()
在 Java(和许多其他语言)中