模型Django民意调查

Mac*_*hon 8 python django django-models

我正在研究Django教程,现在我正在创建一个民意调查.

下面的代码工作正常,直到我想创建选择,由于某种原因,我总是收到此错误消息:

line 22, in __unicode__
return self.question

AttributeError: 'Choice' object has no attribute 'question'
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

这是我的代码:

import datetime
from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question

    def was_published_today(self):
        return self.pub_date.date() == datetime.date.today()



class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice = models.CharField(max_length=200)
    votes = models.IntegerField()

    def __unicode__(self):
        return self.question # this is line 22
Run Code Online (Sandbox Code Playgroud)

Dav*_*cic 10

__unicode__对方法Choice的模型应该是这个样子:

def __unicode__(self):
    return self.poll.question
Run Code Online (Sandbox Code Playgroud)

question属性在Choice模型上不存在,您需要通过poll外键字段来实现它.

不要忘记查看Django的优秀文档,其中显示了许多关于如何处理多对一关系的示例.

编辑

return self.choiceChoice模型__unicode__方法中可能更有意义,因此它输出实际选择而不是轮询问题.

def __unicode__(self):
    return self.choice
Run Code Online (Sandbox Code Playgroud)


Pet*_*ley 7

为了跟进rebus的答案,教程实际上说要为每个模型添加不同的回报:

class Poll(models.Model):
    # ...
    def __unicode__(self):
        return self.question

class Choice(models.Model):
    # ...
    def __unicode__(self):
        return self.choice
Run Code Online (Sandbox Code Playgroud)

你有'self.question'作为两者的回报 - 我认为你做了同样的复制/粘贴错误,或者教程之前有错误;-)