Following backreferences of unknown kinds in NDB

前端 未结 2 1140
刺人心
刺人心 2021-02-09 07:42

I\'m in the process of writing my first RESTful web service atop GAE and the Python 2.7 runtime; I\'ve started out using Guido\'s shiny new ndb API.

However, I\'m unsure

2条回答
  •  别那么骄傲
    2021-02-09 08:09

    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. :-) ]

提交回复
热议问题