Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
481 views
in Technique[技术] by (71.8m points)

python - Object has no attribute _state

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...