hasattr returns always True for app engine ndb entity

281 Views Asked by At

I am applying this answer to my project

This is my ndb entity where is_deleted added later.

class FRoom(ndb.Model):  
    location = ndb.StringProperty(default="")
    is_deleted = ndb.BooleanProperty(default=False) #added later 
    #other fileds

when I do print my entities with logging.info, I have

FRoom(key=Key('FRoom', 5606822106890240), is_deleted=False, location=u'denizli')
FRoom(key=Key('FRoom', 6169772060311552), is_deleted=False, location=u'aydin' )
FRoom(key=Key('FRoom', 6451247037022208), location=u'bursa')

When I do for do

for froom in frooms:
    logging.info(hasattr(froom, 'is_deleted')) # gives always True

but when I do for example:

logging.info(hasattr(froom, 'is_deletedXXX')) #gives me False

What am I doing wrong?

1

There are 1 best solutions below

5
Dan Cornilescu On

This is expected behaviour due to the is_deleted property having the default option set: the datastore will automatically return that default value if the property was not explicitly set.

From the Property Options table:

enter image description here

So for properties for which you set the default option in the model the check if the property exists is unnecessary - it always exists, so you can directly do:

for froom in frooms:
    logging.info(froom.is_deleted)
    # or
    logging.info(getattr(froom, 'is_deleted'))

The hasattr(froom, 'is_deletedXXX') returns False because you don't have a is_deletedXXX property in FRoom's model.