Stina
Stina

Reputation: 509

Serializing ReferenceProperty in Appengine Datastore to JSON

I am using the following code to serialize my appengine datastore to JSON

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


 class commonWordTweets(DictModel):
    commonWords = db.StringListProperty(required=True)
    venue = db.ReferenceProperty(Venue, required=True, collection_name='commonWords')

class Venue(db.Model): id = db.StringProperty(required=True) fourSqid = db.StringProperty(required=False) name = db.StringProperty(required=True) twitter_ID = db.StringProperty(required=True)

This returns the following JSON response

 [
  {
    "commonWords": "[u'storehouse', u'guinness', u'badge', u'2011"', u'"new', u'mayor', u'dublin)']",
    "venue": "<__main__.Venue object at 0x1028ad190>"
  }
]

How can I return the actual venue name to appear?

Upvotes: 1

Views: 651

Answers (1)

Thomas K
Thomas K

Reputation: 40340

Firstly, although it's not exactly your question, it's strongly recommended to use simplejson to produce json, rather than trying to turn structures into json strings yourself.

To answer your question, the ReferenceProperty just acts as a reference to your Venue object. So you just use its attributes as per normal.

Try something like:

cwt = commonWordTweets()   # Replace with code to get the item from your datastore
d = {"commonWords":cwt.commonWords, "venue": cwt.venue.name}
jsonout = simplejson.dumps(d)

Upvotes: 3

Related Questions