【发布时间】:2015-12-19 20:30:31
【问题描述】:
我正在关注 Django 网站上的应用教程,并使用 Python 2.7.5 和 Django 1.8。它建议用户在 models.py 文件中包含一个 unicode 方法,以便在 python shell 中返回可读的输出。
我已将 unicode 方法添加到 Question 和 Choice 类中:
from django.db import models
import datetime
from django.utils import timezone
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days = 1)
def __unicode__(self):
return u"%i" % self.question_text
def __str__(self):
return question_text
class Choice(models.Model):
question = models.ForeignKey(Question)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __unicode__(self):
return u"%i" % self.choice_text
def __str__(self):
return choice_text
这是我从 python shell 的输出:
from polls.models import Question, Choice
>>> Question.objects.all()
[<Question: Question object>]
什么时候真的应该是这样的:
>>> Question.objects.all()
[<Question: What's up?>]
我以前问过这个问题,但没有找到解决办法。请帮忙!
【问题讨论】: