Skip to content

Instantly share code, notes, and snippets.

@kaylarose
Last active December 18, 2015 18:39
Show Gist options
  • Save kaylarose/5826860 to your computer and use it in GitHub Desktop.
Save kaylarose/5826860 to your computer and use it in GitHub Desktop.
Google App Engine NDB Snippets
# Creates a back reference to Unknown kinds in a one-to-many model (from Guido Van Rossum)
# Source: http://stackoverflow.com/questions/10731433/following-backreferences-of-unknown-kinds-in-ndb
class LinkedKeyProperty(ndb.KeyProperty):
def _fix_up(self, cls, code_name):
super(LinkedKeyProperty, self)._fix_up(cls, code_name)
modelclass = ndb.Model._kind_map[self._kind]
collection_name = '%s_ref_%s_to_%s' % (cls.__name__,
code_name,
modelclass.__name__)
setattr(modelclass, collection_name, (cls, self))
# Source: https://developers.google.com/appengine/docs/python/ndb/metadata
google.appengine.ext.ndb import metadata
nses = metadata.get_namespaces()
# Source: http://stackoverflow.com/questions/14192331/how-to-set-an-ndb-keyproperty
class Person(ndb.Expando):
pass
class Favourite(ndb.Expando):
pass
class Picture(ndb.Expando):
pass
person = Person()
person.put()
picture = Picture()
picture.put()
fav = Favourite(
# Personal note: As far as I can tell, parents/ancestors *specifically*
# MUST be in the same Namespace as children.
# I do not believe that this is the case for non-standard relations (i.e. person, picture)
parent=person.key,
person=person.key,
picture=picture.key
)
fav.put()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment