Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google app engine - ndb query to only get a few columns in python

In google app engine, is it possible to query the db to only get certain columns?

For example, I have a Model defined as follows:

class userData(ndb.Model):
    id = ndb.StringProperty()
    name = ndb.StringProperty()
    emailAddress = ndb.StringProperty()

I usually query the db as follows:

userData.query().filter(ndb.GenericProperty('id') == "requiredId").fetch()

But this gives me results which contain id, name and email.

Now I would like to get only id and name but not emailAddress. How can I do that?

Thank you!

like image 725
Krishna Chaitanya Avatar asked Dec 19 '22 13:12

Krishna Chaitanya


1 Answers

What you need is called projection query

Example:

qry = Article.query()
articles = qry.fetch(20, projection=[Article.author, Article.tags])
for article in articles:
  # code here can use article.author, article.tags
  # but cannot use article.title

Your code:

class userData(ndb.Model):
    id = ndb.StringProperty()
    name = ndb.StringProperty()
    emailAddress = ndb.StringProperty()

user = userData.query().filter(ndb.GenericProperty('id') ==  "requiredId")\
                       .fetch(projection=[userData.id, userData.name])

Though I need to quote from the docs:

Projection can be useful; if you only need two small properties each from several large entities, the fetch is more efficient since it gets and deserializes less data.

Think about the above when you use projection queries

P.S.

Also use CapWords convention for class names in python if you want to follow the PEP

like image 156
Jimmy Kane Avatar answered Apr 13 '23 01:04

Jimmy Kane