Django错误:'unicode'对象不可调用

8 投票
1 回答
19192 浏览
提问于 2025-04-16 05:02

我正在尝试从Django官网学习Django的教程,但遇到了一点问题:我需要在我的模型类中添加__unicode__方法,但每当我试图返回该模型的对象时,就会出现以下错误:

in __unicode__
    return self.question()
TypeError: 'unicode' object is not callable

我对Python还比较陌生,对Django更是全新,所以我不太明白我哪里出了问题。如果有人能指出来,我会非常感激。这里有一段代码:

我的models.py文件:

# The code is straightforward. Each model is represented by a class that subclasses django.db.models.Model. Each model has a number of 
# class variables, each of which represents a database field in the model.

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


    class Choice(models.Model):
        poll = models.ForeignKey(Poll) 
        choice = models.CharField(max_length=200) 
        votes = models.IntegerField()

        def __unicode__(self):
            return self.choice()

还有在交互式命令行中的内容:

from pysite.polls.models import Poll, Choice
Poll.objects.all()

1 个回答

29

self.choice 是一个字符串值,但代码试图把它当成一个函数来调用。只需要把后面的 () 去掉就可以了。

撰写回答