Skip to main content
 首页 » 编程设计

python之django 教程——返回通用对象而不是我的文本

2025年05月04日41xiaohuochai

我现在正在学习 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> 

我得到“选择对象”而不是“不多”

这是我现有的 mysite.settings 路径代码:

`类问题(models.Model):

quest_text = models.CharField(max_length=200) 
pub_date = models.DateTimeField('date published') 
 
def __unicode__(self): 
    return self.quest_text 
 
def was_published_recently(self): 
    return self.pub_date >= timezone.now()-datetime.timedelta(days=1) 

类选择(模型。模型):

question = models.ForeignKey(Question) 
choice_text = models.CharField(max_length=200) 
votes = models.IntegerField(default=0) 
 
def __unicode___(self): 
    return self.choice_text` 

现在我得到了这个:

In [17]: Question.objects.all() Out[17]: <repr(<django.db.models.query.QuerySet at 0x10530bbd0>) failed: AttributeError: 'Question' object has no attribute 'unicode'>

请您参考如下方法:

自 <Choice: Choice object>不是对象的有用表示,您可以添加 __str__() (或 __unicode__() 对于 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