【问题标题】:Python - Google App Engine - Get model ID in DictPython - Google App Engine - 在字典中获取模型 ID
【发布时间】:2011-08-07 11:52:32
【问题描述】:

在我的 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 对象的一部分?

【问题讨论】:

  • 那么您希望主键字段属于这本字典吗?
  • 数据存储需要能够存储字典。有解决方法,但Google 已经对此提出了功能请求。如果您对此功能感兴趣,请点击问题编号旁边的星号进行投票。

标签: python json google-app-engine dictionary


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 2011-05-12
    • 2013-01-05
    • 2010-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-08
    • 1970-01-01
    相关资源
    最近更新 更多