本文介绍了django中的_unicode()方法出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在模型中添加了 unicode ()方法,但是在交互式环境中显示所有对象时,该方法不起作用。
I'm adding a unicode() method to my model, however when displaying all objects in the interactive it's not working.
import datetime
from django.db import models
from django.utils import timezone
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def _unicode_(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def _unicode_(self):
return self.choice
# Create your models here.
(InteractiveConsole
>>> from polls.models import Poll, Choice
>>> Poll.objects.all()
[<Poll: Poll object>]
推荐答案
django文档向您展示了如何在模型中指定unicode方法:
The django docs show you how to specify a unicode method in your model:
https://docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs#other-model-instance-methods
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
注意:这些是双下划线,在您的示例中,您仅使用
Note: These are DOUBLE underscores, where in your example you are only using single underscores.
它是标准的python特殊cl屁股方法,
Its a standard python special class method, as listed here
这篇关于django中的_unicode()方法出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!