Following backreferences of unknown kinds in NDB
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping
--
Chapters
00:00 Question
02:23 Accepted answer (Score 8)
03:37 Answer 2 (Score 2)
03:51 Thank you
--
Full question
https://stackoverflow.com/questions/1073...
Question links:
[previous SO inquiry]: https://stackoverflow.com/questions/9917...
Answer 1 links:
[ndb.StructuredProperty]: https://developers.google.com/appengine/...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #googleappengine #googleclouddatastore #appenginendb
#avk47
ACCEPTED ANSWER
Score 8
Interesting question! So basically you want to look at the Contact class and find out if there is some other model class that has a KeyProperty referencing it; in this example PhoneNumber (but there could be many).
I think the solution is to ask your users to explicitly add this link when the PhoneNumber class is created.
You can make this easy for your users by giving them a subclass of KeyProperty that takes care of this; e.g.
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))
Exactly how you pick the name for the collection and the value to store there is up to you; just put something there that makes it easy for you to follow the link back. The example would create a new attribute on Contact:
Contact.PhoneNumber_ref_contact_to_Contact == (PhoneNumber, PhoneNumber.contact)
[edited to make the code working and to add an example. :-) ]
ANSWER 2
Score 2
Sound like a good use case for ndb.StructuredProperty.