在Appengine中,我试图自动计算属性值并与对象一起存储.
我有一个类,矩形,它有宽度,高度和面积.显然该区域是宽度和高度的函数,但我希望它是一个属性,因为我想用它来进行排序.所以我尝试修改put()函数以在存储Rectangle时隐藏该区域,如下所示:
class Rectangle(db.Model): width = db.Integerproperty() height = db.Integerproperty() area = db.Integerproperty() def put(self,**kwargs): self.area = self.width * self.height super(Rectangle,self).put(**kwargs)
当我直接在Area对象上调用put()时,这个工作原理:
re1 = Rectangle(width=10,height=10) re1.put() print re1.area # >> 10
但是当我使用db.put()时(例如,一次性保存很多),这会中断.
re2 = Rectangle(width=5,height=5) db.put(re2) print re2.area # >> None
“偷偷摸摸”计算值的正确方法是什么?
解决方法
不要覆盖put – 如你所见,它很脆弱,如果你调用db.put而不是模型的put函数,就不会调用它.
幸运的是,App Engine提供了ComputedProperty,使您的用例非常简单:
class Rectangle(db.Model): width = db.Integerproperty() height = db.Integerproperty() @db.ComputedProperty def area(self): return self.width * self.height