我正在为我的模型添加 unicode ()方法,但是当在交互式中显示所有对象时,它无法正常工作。
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>]
答案 0 :(得分:3)
他们需要被命名为__unicode__
(两边都有两个下划线)。这是Python保留方法的一个尴尬细节,通过查看它们并不是很明显。
答案 1 :(得分:2)
django文档向您展示如何在模型中指定unicode方法:
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)
注意:这些是DOUBLE下划线,在您的示例中,您只使用单个下划线。
它是一个标准的python特殊类方法as listed here