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

Sri*_*Sri 1 python google-app-engine json 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()])
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*loe 5

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

class MyModel(db.Model):
    def to_dict(self):
        return db.to_dict(self, {'id':self.key().id()})
Run Code Online (Sandbox Code Playgroud)

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