4

我正在从 https://docs.djangoproject.com/en/dev/intro/tutorial01/编写我的第一个 django 应用程序, 我遇到了 2 个问题。

我的 Models.py 是

从 django.db 导入模型

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def _unicode_(self):
        return self.question self.question                                                                                                                                                   
class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
     def _unicode_(self):
        return self.question 

我的第一个错误是当我这样做的时候

 python manage.py shell
 from mysite.myapp.models import Poll,Choice
 p = Poll(question="What Your Name",pub_date"1990-02-04")
 p.save()
 Poll.objects.all()
 [<Poll: Poll object>, <Poll: Poll object>]

为什么它不显示 { 民意调查:怎么了?} 反而

 [<Poll: Poll object>, <Poll: Poll object>]

我的第二个问题是当我输入

 p = Poll.objects.get(id=1)
 p.question.objects.all()

我得到这个错误

 AttributeError: 'unicode' object has no attribute 'objects'

我如何解决它?

4

2 回答 2

2
  1. 您必须定义__unicode__模型的方法,而不是_unicode_.此外,您给出的代码 return self.question self.question语法无效。

  2. p是一个 poll 实例,p.question是 CharField 不是 ForeignKey,没有属性对象。p有对象,调用p.objects.all()效果很好。

于 2013-02-12T05:46:59.910 回答
1

1> 它__unicode__不是_unicode_

Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __unicode__(self):
        return self.question, self.pub_date

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __unicode__(self):
        return self.choice_text

2> objects 函数是文档实例的属性而不是字段,p.questions 是文档字段,

于 2013-02-12T05:52:41.633 回答