Python django教程--返回泛型对象而不是我的文本
我现在正在学习django教程,当我要为我的投票创建一个选项时,我会继续返回通用选项,而不是我输入的文本Python django教程--返回泛型对象而不是我的文本,python,django,django-models,read-eval-print-loop,Python,Django,Django Models,Read Eval Print Loop,我现在正在学习django教程,当我要为我的投票创建一个选项时,我会继续返回通用选项,而不是我输入的文本 In [19]: q.choice_set.all() Out[19]: [] In [20]: q.choice_set.create(choice_text='Not much', votes=0) Out[20]: <Choice: Choice object> 课程选择(models.Model): 现在我明白了: [17]中的:Question.objects.al
In [19]: q.choice_set.all()
Out[19]: []
In [20]: q.choice_set.create(choice_text='Not much', votes=0)
Out[20]: <Choice: Choice object>
课程选择(models.Model):
现在我明白了:
[17]中的:Question.objects.all()
Out[17]:
您调用的方法是建立并返回一个新的Choice
对象,而不是一个新的str
实例。因此,您在REPL中看到的正是您应该看到的:
是Choice实例的默认表示形式
如果您不喜欢默认表示法,请实现\uuuuuuunicode\uuuuuuu
和\uuuu repr\uuuuuuu
方法(或Py3k+的\uuuuuuuu str\uuuuuu
:
本教程后面可能会介绍这一点,因此在这里提问之前完成它是一个好主意。您调用的方法是建立并返回一个新的
选择
对象,而不是一个新的str
实例。因此,您在REPL中看到的正是您应该看到的:
是Choice实例的默认表示形式
如果您不喜欢默认表示法,请实现\uuuuuuunicode\uuuuuuu
和\uuuu repr\uuuuuuu
方法(或Py3k+的\uuuuuuuu str\uuuuuu
:
本教程后面可能会介绍这一点,因此在这里提问之前完成它是一个好主意。由于
不是对象的有用表示形式,因此您可以向每个模型添加\uu str\uuuuuuuuuuuuuuo()
方法
class Question(models.Model):
#.. Other model stuff you already have
def __str__(self):
return self.question_text
class Choice(models.Model):
# ... Other model stuff you already have
def __str__(self):
return self.choice_text
由于
不是对象的有用表示形式,因此可以向每个模型添加\uuuu str\uuuu()
(或\uuuu unicode\uuuuu()
(对于Python 2)方法
class Question(models.Model):
#.. Other model stuff you already have
def __str__(self):
return self.question_text
class Choice(models.Model):
# ... Other model stuff you already have
def __str__(self):
return self.choice_text
我已经将unicode添加到我的模型中,请参见以下内容:
classchoice(models.Model):question=models.ForeignKey(question)Choice\u text=models.CharField(max\u length=200)vots=models.IntegerField(默认值=0)def\uuuuuunicode\uuuuu(self):返回self.Choice\u text
请更新问题,注释系统不保留格式,对于python这样的语言来说这是必须的。好吧,忘记了\uuuu repr\uuu
方法。我已经将unicode添加到我的模型中,请参见下面的:类选择(models.Model):问题=模型。外键(问题)选择\u文本=模型。字符域(最大长度=200)投票=models.IntegerField(默认值=0)def\uuuu unicode\uuuuu\uuuuu(self):返回self.choice\u text
请更新问题,注释系统不保留格式,对于python这样的语言来说这是必须的。确定,忘记了\uuuu repr\uuuu
方法。在使用unicode和Python 3时遇到了这个问题,结果非常好。谢谢在使用unicode和Python 3时遇到了这个问题,结果非常好。谢谢
class Choice(models.Model):
# ... other stuff you already have here ...
def __unicode__(self):
return self.choice_text
def __repr__(self):
return self.unicode()
class Question(models.Model):
#.. Other model stuff you already have
def __str__(self):
return self.question_text
class Choice(models.Model):
# ... Other model stuff you already have
def __str__(self):
return self.choice_text