Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google app engine ndb: put() and then query(), there is always one less item

I wonder if anybody has encountered the strange problem on Google App Engine's NDB: after creating a new entity and saving it by put(); and then query() immediately, there is always one less item. For example,

class Item(ndb.Model):
    ...
    ...

items = Item.query().fetch()
length1 = len(items)
item = Item()
item.put()
items = Item.query().fetch()
length2 = len(items)

In the above, length1 is always equal to length2. However, length2 will be corrected when revisiting the same HTML page later. What is the problem? Thanks.

like image 204
Randy Tang Avatar asked Mar 17 '13 12:03

Randy Tang


Video Answer


2 Answers

This is expected behaviour; your queries above are only eventually consistent. That is, you're not guaranteed to get the very latest results when querying.

You can get around this by using an ancestor query (see the link above). For your example, you'd need to give each of your items a parent entity and then use Item.query().ancestor(theParentEntity).fetch().

like image 166
Jesse Rusak Avatar answered Oct 02 '22 14:10

Jesse Rusak


As @JesseRusak said, you need a Dummy ancestor to solve this little problem (I had the same problem that you recently).

But I didn't make a new DummyEntity, just only a DummyKey for a DummyAncestor. Try this for your problem:

class Item(ndb.Model): ... ... items = Item.query(ancestor=ndb.Key(Item, 'Items')).fetch() length1 = len(items) item = Item(parent=ndb.Key(Item, 'Items')) item.put() items = Item.query(ancestor=ndb.Key(Item, 'Items')).fetch() length2 = len(items)

At least in my case, the DummyAncestor worked.

like image 45
Eagle Avatar answered Oct 02 '22 15:10

Eagle