Obligatory blog example setup; Authors
have Posts
class Author(db.Model):
name = db.StringProperty()
class Post(db.Model):
author = db.ReferenceProperty()
article = db.TextProperty()
bob = Author(name='bob')
bob.put()
first thing to remember is that regular get/put/delete on a single entity group (including single entity) will work as expected:
post1 = Post(article='first article', author=bob)
post1.put()
fetched_post = Post.get(post1.key())
# fetched_post is latest post1
You will only be able notice inconstancy if you start querying across multiple entity groups. Unless you have specified a parent
attribute, all your entities are in separate entity groups. So if it was important that straight after bob
creates a post, that he can see there own post then we should be careful with the following:
fetched_posts = Post.all().filter('author =', bob).fetch(x)
# fetched_posts _might_ contain latest post1
fetched_posts
might contain the latest post1
from bob
, but it might not. This is because all the Posts
are not in the same entity group. When querying like this in HR you should think "fetch me probably the latest posts for bob".
Since it is important in our application that the author can see his post in the list straight after creating it, we will use the parent
attribute to tie them together, and use an ancestor
query to fetch the posts only from within that group:
post2 = Post(parent=person, article='second article', author=bob)
post2.put()
bobs_posts = Post.all().ancestor(bob.key()).filter('author =', bob).fetch(x)
Now we know that post2
will be in our bobs_posts
results.
If the aim of our query was to fetch "probably all the latest posts + definitely latest posts by bob" we would need to do another query.
other_posts = Post.all().fetch(x)
Then merge the results other_posts
and bobs_posts
together to get the desired result.