Django 'unicode' object has no attributes 'objects'
I am writing my first django app from https://docs.djangoproject.com/en/dev/intro/tutorial01/ and I am experiencing 2 problems.
My .py models are
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 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
My first mistake when I do
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>]
Why doesn't he show {Poll: What? } instead of
[<Poll: Poll object>, <Poll: Poll object>]
My second question is when I type
p = Poll.objects.get(id=1)
p.question.objects.all()
I am getting this error message
AttributeError: 'unicode' object has no attribute 'objects'
How to fix it?
source to share
-
you should define your method on
__unicode__
your model, not_unicode_
. Also, the code you providedreturn self.question self.question
is not valid in the syntax. -
p
is a poll instance,p.question
is a CharField, not a ForeignKey, has no attribute objects.p
has objects, the callp.objects.all()
works well.
source to share
1> its __unicode__
not_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> The objects function is a property of the document instance, not the fields, p.questions is the document field,
source to share