Django 错误 'unicode' 对象没有属性 'objects' [英] Django error 'unicode' object has no attribute 'objects'

查看:36
本文介绍了Django 错误 'unicode' 对象没有属性 'objects'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写我的第一个 django 应用程序https://docs.djangoproject.com/en/dev/intro/tutorial01/我遇到了两个问题.

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'

我该如何解决?

推荐答案

  1. 你必须定义你的模型的 __unicode__ 方法,而不是 _unicode_.另外,你给的代码 return self.question self.question 语法无效.

  1. you must define your __unicode__ method of your model, not _unicode_.In addition, the code you given return self.question self.question is syntax invalid.

p 是一个 poll 实例,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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆