本文介绍了对象没有属性_state的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 'Sheep'对象没有属性_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)

我必须做什么?

解决方案,您必须非常小心地覆盖 __ init __ 以具有非可选参数。记住,每次从查询器获取对象时都会被调用!



这是您想要的正确代码:



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ models models models models models models models models models models models models models models models models models models models models models models models models models models models models models models models models models models $($)
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上设置抽象选项。这确保了一个表不是为动物创建的,而仅为羊(等)而创建。如果没有设置抽象,那么将创建一个动物表,并且羊类将被赋予它自己的表和一个自动动物字段,它将是Animal模型的外键。


I'm developing Django application, and I have following error

'Sheep' object has no attribute _state

My models are constructed like this

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)

What I must do?

解决方案

firstly, you must be very careful overriding __init__ to have non-optional arguments. remember it will be called every time you get an object from a queryset!

this is the correct code you want:

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()

I highly suggest setting the abstract option on Animal if you will only ever be using subclasses of this object. This ensures a table is not created for animal and only for Sheep (etc..). if abstract is not set, then an Animal table will be created and the Sheep class will be given it's own table and an automatic 'animal' field which will be a foreign key to the Animal model.

这篇关于对象没有属性_state的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 07:33