【问题标题】:Django error 'unicode' object has no attribute 'objects'Django错误'unicode'对象没有属性'objects'
【发布时间】:2013-01-27 09:12:21
【问题描述】:

我正在编写我的第一个 django 应用程序 https://docs.djangoproject.com/en/dev/intro/tutorial01/ 我遇到了 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'

我该如何解决?

【问题讨论】:

    标签: django attributeerror


    【解决方案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 是文档字段,

    【讨论】:

    • 没有self.question可供选择
    【解决方案2】:
    1. 你必须定义你的模型的__unicode__方法,而不是_unicode_。另外,你给return self.question self.question的代码语法无效。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2021-10-22
      • 2019-02-25
      • 2013-01-18
      • 2014-08-25
      • 1970-01-01
      相关资源
      最近更新 更多