How to query for newly created property in NDB?

六月ゝ 毕业季﹏ 提交于 2019-12-12 05:34:48

问题


I had NDB class before and added new property receive_news just now:

class User(ndb.Model):
    '''
    Index
        Key: user_id
    '''
    lang = ndb.StringProperty(required=None, indexed=True)
    receive_news = ndb.BooleanProperty(required=None, indexed=True)

I would like to get list of users, who would like to receive my news (all users currently). I tried the following options:

keys = User.query(User.receive_news != True).fetch(keys_only=True)
keys = User.query(User.receive_news == None).fetch(keys_only=True)

both returns 0. How should I work properly with this new property?


回答1:


Datastore indexes are only updated when entities are being written to the datastore, so only entities written after the new index was created will be added to it.

To have the pre-existing entities added to the index (so that they can be found by the query) you'll have to get and then re-write them. Maybe using something along these lines (you'll have to split it in separate requests/tasks if they are too many)

keys = []
for user in ndb.get_multi(User.query().fetch(keys_only=True)):
    if  user.receive_news is None:
        user.receive_news = True
        keys.append(user.key)
ndb.put_multi(keys)


来源:https://stackoverflow.com/questions/45399187/how-to-query-for-newly-created-property-in-ndb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!