Python 对象没有属性_state

Python 对象没有属性_state,python,django,Python,Django,我正在开发Django应用程序,我有以下错误 'Sheep' object has no attribute _state 我的模型是这样构造的 class Animal(models.Model): aul = models.ForeignKey(Aul) weight = models.IntegerField() quality = models.IntegerField() age = models.IntegerField() def __i

我正在开发Django应用程序,我有以下错误

'Sheep' object has no attribute _state
我的模型是这样构造的

class Animal(models.Model):
    aul = models.ForeignKey(Aul)
    weight = models.IntegerField()
    quality = models.IntegerField()
    age = models.IntegerField()

    def __init__(self,aul):
        self.aul=aul
        self.weight=3
        self.quality=10
        self.age=0

    def __str__(self):
        return self.age


class Sheep(Animal):
    wool = models.IntegerField()

    def __init__(self,aul):
        Animal.__init__(self,aul)

我必须做什么?

首先,您必须非常小心地重写
\uuuu init\uuu
以使用非可选参数。记住,每次从queryset获取对象时都会调用它

这是您需要的正确代码:

class Animal(models.Model):
   #class Meta:          #uncomment this for an abstract class
   #    abstract = True 
   aul = models.ForeignKey(Aul)
   weight = models.IntegerField(default=3)
   quality = models.IntegerField(default=10)
   age = models.IntegerField(default=0)

   def __unicode__(self):
       return self.age

class Sheep(Animal):
   wool = models.IntegerField()
如果您只使用这个对象的子类,我强烈建议您在Animal上设置abstract选项。这确保了表格不是为动物创建的,而是只为绵羊(等)创建的。如果未设置abstract,则将创建一个动物表,并为Sheep类提供它自己的表和一个自动的“Animal”字段,该字段将是动物模型的外键

建议您在模型中使用
\uuuu init\uuu
方法:

您可能会试图通过重写
\uuuu init\uuu
方法来定制模型。但是,如果这样做,请注意不要更改调用签名,因为任何更改都可能会阻止保存模型实例。不要覆盖
\uuuu init\uuuuu
,请尝试使用以下方法之一:

  • 在模型类上添加classmethod
  • 在自定义管理器上添加方法(通常首选)