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.
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With