Django民意调查App:AttributeError:'Choice'对象没有属性'question_text'

时间:2015-05-13 15:17:30

标签: python django

当我收到此错误时,我正在Django网站上进行教程。 我使用的是OS X 10.10。

>>> q.choice_set.create(choice_text='Not much', votes=0)
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Library/Python/2.7/site-packages/Django-1.7.8-py2.7.egg/django/db/models/base.py", line 458, in __repr__
    u = six.text_type(self)
  File "/Users/anushrutgupta/Documents/IMG/Django/mysite/polls/models.py", line 22, in __str__
    return self.choice_text
AttributeError: 'Choice' object has no attribute 'question_text'
>>> 

我的models.py:

import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):  
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() -datetime.timedelta(days=1)

class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self):   
        return self.choice_text

模特出了什么问题?

5 个答案:

答案 0 :(得分:4)

models.py第22行的代码中看起来像是一个拼写错误,你有return self.question_text但它应该是return self.choice_text

编辑:我发现您使用的是Python 2.7,使用Python 2,您需要使用__unicode__而不是__str__

  

__str____unicode__

     

在Python 3上,它很简单,只需使用__str__()

     

在Python 2上,您应该定义返回unicode值的__unicode__()方法。 Django模型有一个默认的__str__()方法,它调用__unicode__()并将结果转换为UTF-8字节串。这意味着unicode(p)将返回Unicode字符串,str(p)将返回字节字符串,字符编码为UTF-8。 Python做的恰恰相反:object有一个__unicode__方法,它调用__str__并将结果解释为ASCII字节串。这种差异会造成混乱。

     

如果所有这些都是胡言乱语,请使用Python 3。

答案 1 :(得分:2)

因此,在定义q时,如果您尚未使用.get(),请使用.filter()
您可以在官方文档中阅读.get().filter()之间的区别。
据我所知, import com.sun.jna.Native; import com.sun.jna.NativeLibrary; import uk.co.caprica.vlcj.binding.LibVlc; import uk.co.caprica.vlcj.discovery.NativeDiscovery; import uk.co.caprica.vlcj.player.MediaPlayer; import uk.co.caprica.vlcj.player.MediaPlayerFactory; import uk.co.caprica.vlcj.runtime.RuntimeUtil; import uk.co.caprica.vlcj.runtime.x.LibXUtil; public class SaveStream { public static void main(String[] args) throws Exception { NativeDiscovery nd = new NativeDiscovery(); if (!nd.discover()) { System.out.println("VLC not found"); System.exit(-1); } String vlcLibName = RuntimeUtil.getLibVlcName(); String vlcLibCoreName = RuntimeUtil.getLibVlcCoreName(); Native.loadLibrary(vlcLibName, LibVlc.class); MediaPlayerFactory factory = new MediaPlayerFactory(); MediaPlayer player = factory.newHeadlessMediaPlayer(); String mrl = "rtsp://username:password@190.100.100.189:554"; String options = ":sout=#transcode{vcodec=h264,venc=x264{cfr=16},scale=1,acodec=mp4a,ab=160,channels=2,samplerate=44100}:file{dst=test.avi}"; player.playMedia(mrl, options); Thread.sleep(20000); // <--- sleep for 20 seconds, you should use events - but this is just a demo player.stop(); player.release(); factory.release(); } } 不会保留对象供您使用其属性来操纵它。

答案 2 :(得分:0)

我找到了解决这个问题的方法,我也犯了同样的错误 当你定义变量q时,

q = Question.objects.get(pk=1) #it should be like this
q.choice_set.all() #this will show an empty list (only if it's empty)
q.choice_set.create(choice_text="sheela ki jawani", votes=0) #and so on

我正在做第一步错误地定义q而不是.get(pk = 1),我正在使用

q = Question.objects.all() #this is wrong

答案 3 :(得分:0)

我正在做同样的练习,根据你的代码我设法使我的工作。 (显示问题:什么了?)。我必须说,我发现教程中的逐步说明非常令人困惑。

我的代码有两行:

 from __future__ import unicode_literals # future between underscores, 2 on each side

from django.utils.encoding import python_2_unicode_compatible

答案 4 :(得分:0)

因此,两个表使用外键“问题”链接在一起

要使表“ Question”与表“ Choices”相关联,您需要在ForeignKeyField中添加一个名为“ related_name”的参数

例如,对于要用1或n个选项映射的问题,可以使用相关名称

代码如下:

class Choices(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE, 
    related_name="choice_set")
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)