I am working through the Django tutorials, and now I am at creating a poll.
The code below works fine until I want to create 开发者_开发知识库choices, where for some reason I always get this error message:
line 22, in __unicode__
return self.question
AttributeError: 'Choice' object has no attribute 'question'
What am I doing wrong?
Here's my code:
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
The __unicode__
method on the Choice
model should look something like:
def __unicode__(self):
return self.poll.question
question
attribute does not exist on the Choice
model, you need to reach for it over the poll
foreign key field.
Don't forget to check out Django's great documentation that shows many examples on how to handle many to one relationships.
Edit
It would probably make more sense to return self.choice
in Choice
model __unicode__
method so it outputs the actual choice not the Poll question.
def __unicode__(self):
return self.choice
To follow up on rebus's answer, the tutorial actually says to add different returns to each model:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
You had 'self.question' as the return for both - I'm thinking you made the same copy/paste error I did, or the tutorial previously had that error ;-)
It should be:
def __unicode__(self):
return self.poll.question
Because poll is a related model that contains the question.
This is due to a Human Brain error or a copy/paste error. We/You thought that both functions were same and copy-pasted the same code for both, but there was one word different in both.
replace question
to choice
in line 22
精彩评论