Django错误"unicode"对象没有属性"objects" [英] Django error 'unicode' object has no attribute 'objects'
问题描述
我正在从中编写我的第一个Django应用程序 https://docs.djangoproject.com/en/dev/intro/tutorial01/一个> 我遇到2个问题.
I'm writing my first django app from https://docs.djangoproject.com/en/dev/intro/tutorial01/ and i'm experiencing 2 problems.
我的Models.py是
My Models.py are
从django.db导入模型
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()
我得到这个错误
AttributeError: 'unicode' object has no attribute 'objects'
我该如何解决?
推荐答案
-
您必须定义模型的
__unicode__
方法,而不是_unicode_
.此外,您赋予return self.question self.question
的代码语法无效.
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
是一个轮询实例,p.question
是CharField而不是ForeignKey,没有属性对象. p
有对象,调用p.objects.all()
效果很好.
p
is a poll instance, p.question
is CharField not ForeignKey, has no attribute objects. p
has objects, call p.objects.all()
works well.
这篇关于Django错误"unicode"对象没有属性"objects"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!