0

我的数据库中有一张表,区域

class region(models.Model):
    region_name = models.CharField(primary_key=True,max_length=50, null=False)

    @classmethod
    def __unicode__(self):
        return "hello"

当我试图通过管理界面将几个新的区域实例添加到数据库中时,所有现有区域的标题都是“hello”,所以我将__unicode__(self)函数更新为

@classmethod
def __unicode__(self):
    return u'%s' %(self.region_name)

但现在管理员显示

Exception Type: AttributeError
Exception Value:    
type object 'region' has no attribute 'region_name'

我检查了我的数据库,并且区域表中有 region_name。任何人都可以帮助为什么会发生这种情况?

4

1 回答 1

4

你不应该使用@classmethod. 只需删除函数的@classmethod装饰器__unicode__;装饰的函数的第一个参数@classmethod是类本身,而不是您的实例的模型region实例。

这个答案很好地概述了Python 中装饰器的用途和使用classmethod以及函数装饰器。staticmethod

于 2013-05-29T08:53:35.083 回答