Django error 'unicode' object has no attribute 'objects'

一笑奈何 提交于 2020-01-14 18:46:13

问题


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:


  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.

  2. p is a poll instance, p.question is CharField not ForeignKey, has no attribute objects. p has objects, call p.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!