Sri
Sri

Reputation: 5845

Python - Google App Engine - Get model ID in Dict

In my Google App Engine - Python app, I've got a to_dict() to allow JSON serialization of my models.

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()])

How do I ensure that modelInstance.key().id() is part of the dict, hence part of the JSON object?

Upvotes: 1

Views: 1462

Answers (1)

Chris Farmiloe
Chris Farmiloe

Reputation: 14185

There's A handy to_dict method in ext.db, you could update your method to something like:

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

You might want to check if your model is is_saved before trying to get the id though.

Upvotes: 5

Related Questions