MR22
MR22

Reputation: 125

Query statement in get_by_id (ndb, GAE)

I'm using Google App Engine with webapp2 and Python.

I have a User model with a deleted field:

class User(ndb.Model):
    first_name = ndb.StringProperty()
    last_name = ndb.StringProperty()
    email = ndb.StringProperty()
    deleted = ndb.BooleanProperty(default=False)

I'd like to get a User object by calling User.get_by_id() but I would like to exclude objects that have deleted field True. Is it possible to do this with the normal get_by_id() function?

If not, could I override it?

Or should I create a custom class method, smth like get_by_id_2() that does a normal .get() query like this: User.query(User.key.id()==id, User.deleted==False).get()?

Would you reccomend something else instead?

Upvotes: 1

Views: 181

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600059

A query is significantly slower than a get, and is subject to eventual consistency. You should probably use the normal get_by_id and check deleted afterwards. You certainly could wrap that up in a method:

@classmethod
def get_non_deleted(cls, id):
    entity = cls.get_by_id(id)
    if entity and not entity.deleted:
        return entity

Upvotes: 3

Related Questions