问题
I'm writing my first django app from https://docs.djangoproject.com/en/dev/intro/tutorial01/ and i'm experiencing 2 problems.
My Models.py 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 Error is 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 it show { Poll: What's up? } instead
[<Poll: Poll object>, <Poll: Poll object>]
My second question is when i type
p = Poll.objects.get(id=1)
p.question.objects.all()
I get this errror
AttributeError: 'unicode' object has no attribute 'objects'
how do i fix it?
回答1:
you must define your
__unicode__
method of your model, not_unicode_
.In addition, the code you givenreturn self.question self.question
is syntax invalid.p
is a poll instance,p.question
is CharField not ForeignKey, has no attribute objects.p
has objects, callp.objects.all()
works well.
回答2:
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> objects function is a property of a document instance not a field, p.questions is a document field,
来源:https://stackoverflow.com/questions/14826183/django-error-unicode-object-has-no-attribute-objects