Python - Google App Engine - 在Dict中获取模型ID

时间:2011-08-07 11:52:33

标签: python json google-app-engine dictionary

在我的Google App Engine - Python应用程序中,我有一个to_dict()来允许我的模型进行JSON序列化。

class BaseModel(db.Model):
  createdOn = db.DateTimeProperty(auto_now_add=True)
  createdBy = db.UserProperty(auto_current_user_add=True)
  modifiedOn = db.DateTimeProperty(auto_now_add=True)
  modifiedBy = db.UserProperty(auto_current_user=True)

  def to_dict(self):
    return dict([(p, unicode(getattr(self, p))) for p in self.properties()])

我如何确保modelInstance.key()。id()是dict的一部分,因此是JSON对象的一部分?

1 个答案:

答案 0 :(得分:5)

to_dict中有一个方便的ext.db方法,您可以将方法更新为:

class MyModel(db.Model):
    def to_dict(self):
        return db.to_dict(self, {'id':self.key().id()})

在尝试获取id之前,您可能想要检查您的模型是否为is_saved。