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>]

2番目の質問は、入力するときです

 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はポーリング インスタンスでp.questionあり、ForeignKey ではなく CharField であり、属性オブジェクトはありません。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> オブジェクト関数はフィールドではなくドキュメント インスタンスのプロパティであり、p.questions はドキュメント フィールドです。

于 2013-02-12T05:52:41.633 に答える