The App Engine documentation on NDB caching indicates that caching is enabled by default:
NDB automatically caches data that it writes or reads (unless an application configures it not to).
I hope this means that I can rely on it to manage key-related models in a cost-effective and performant way. Here's a simple example involving two models with a one-to-many relationship.
A user model (has many comments):
class User(ndb.Model):
name = ndb.StringProperty(required=True)
email = ndb.StringProperty(required=True)
def comments(self, limit=25):
return UserComment.query(UserComment.user_key == self.key) \
.order(-UserComment.created_at) \
.fetch(limit)
A comment model (each comment belongs to a user):
class UserComment(ndb.Model):
user_key = ndb.KeyProperty(required=True)
text = ndb.StringProperty(required=True)
created_at = ndb.DateTimeProperty(auto_now_add=True)
@property
def user(self):
return self.user_key.get()
And a template where a comment is displayed and includes two references to comment.user:
<div class="comment">
<div class="body">
{{ comment.text }}
</div>
<div class="footer">
by {{ comment.user.name }} ({{ comment.user.email }})
</div>
</div>
Is this a sane pattern? Will each reference to comment.user.name and comment.user.email incur a separate query cost or can the automatic NDB cache be trusted to avoid or minimize this?
Similarly, with the User.comments method, can automated caching be trusted minimize costs? Or is it advisable to add code that explicitly uses memcache?