tales of app engine: how to reference an ndb entity from a db entity

24th September 2013

approach one: make a custom property that converts between ndb and db keys.

https://gist.github.com/marcia/6695509

this is OK, but db validation will complain when you try to build queries that filter by  ndb key. this approach does work in the bare-bones case where you have a db entity handy, and then get the referenced ndb entities via the custom property. (thank goodness for ben ko for asking me to test that!)

approach two: store the urlsafe version of the ndb entity’s key as a db.StringProperty.

this is OK, but annoying in that you have to remember to convert from string to ndb.Key and then get the entity. and do the reverse when you assign.

approach three: rewrite your entire codebase to use ndb.

this is OK, but only if your codebase is two lines. oh ndb.KeyProperty!

is there an approach four that is not a compromise at all?

You can leave a response, or trackback from your own site.

2 Responses to “tales of app engine: how to reference an ndb entity from a db entity”

  1. Ben Alpert says:

    I would make a db KeyProperty class (or use the one from aetycoon) and just always convert to and from ndb and db keys. This is like your approach two but feels a little nicer since there aren’t any strings involved. I also hear that you guys have a library called compat_key that makes such conversions a little easier.

  2. Marcia says:

    @alpert – hello! yes, i love compat_key! storing a db.KeyProperty works too, though how annoying that we have to remember to convert back and forth. also it might be a trap for other people to see a db.Key who might expect then that it corresponds to a db entity that they could just then db.get. (whereas a urlsafe key is annoying but at least you’re perhaps forced to wonder what type of entity it corresponds to). :(

Leave a Reply