pythonflaskgoogle-cloud-datastoreapp-engine-ndb

writing ndb query to return the entity key along with the entity


I have an ndb User model:

class User(ndb.Model):
    active = ndb.BooleanProperty(default=True,required=True)
    email= ndb.StringProperty(required=True)

that I call in order to retrieve a JSON file with all my users

@app.route('/get_users')
@login_required
def get_user_data():
    users = json.dumps([u.to_dict() for u in User.query().fetch()])
    return users

The output return looks like this:

[{"email": "user@email.com"},{"email": "user2@email.com"}....]

I would like to pass the ID of each user into the object so I can later on use it to query individual users. Ideally, I want to have an output that looks like this:

[{"email": "user@email.com", "id": xxxxxx},{"email": "user2@email.com", "id": xxxxxx}....]

I tried adding the following declaration into my model class: id = ndb.KeyProperty()

but I'm getting null values instead of retrieving the actual ID value from the datastore entities.

How do I go about pulling the keys of all users and adding them into the returned objects?


Solution

  • You could extend User.to_dict to optionally include the key:

    def to_dict(self, include=None, exclude=None, include_key=False):
        d = super().to_dict(include=include, exclude=exclude)
        if include_key:
            d['key'] = self.key.urlsafe().decode() # or some other JSON-friendly version of the key
        return d
    

    Then change your code, like this:

    users = json.dumps([u.to_dict(include_key=True) for u in User.query().fetch()])
    

    The key can be reconstituted from its urlsafe key representation like this (docs):

    >>> ndb.Key(urlsafe=b"agdleGFtcGxlcgsLEgRLaW5kGLkKDA")
    Key('Kind', 1337, project='example')