我正在关注Django网站上的应用教程,并使用带有Django 1.8的Python 2.7.5。它建议用户在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?>]
我之前已经问过这个问题,但还没有找到解决方案。请帮忙!
答案 0 :(得分:2)
您不需要同时使用__unicode__
和__str__
。在Python 2.7中,您只需使用__str__
。您可以删除__unicode__
,然后单独使用__str__
。 __unicode__
用于python 3。
在文档here
中详细了解相关信息