简体   繁体   中英

How can I create functions that work for different Model classes in GAE?

I have multiple classes for which I have special functions that query ndb in a shorter way, like in this example:

class SomeModel(ndb.Model):
    xcode = ndb.StringProperty('c')
    descr = ndb.StringProperty('d')
    client = ndb.KeyProperty('cl')
    order = ndb.IntegerProperty('o')
    mod = ndb.DateTimeProperty(auto_now=True)

    @classmethod
    def q_base(cls, ancestor):
        return cls.query(ancestor=ancestor).order(cls.codigo)

The function q_base saves some space and makes the code in the handlers look clearer. But since quite a few models need this exact function, I have to repeat it multiple times, which is a problem.

How can I solve it? Can I just make a BaseClass(ndb.Model), add the functions there and make every other model inherit from it? Or do I have to use PolyModel for that? How would that look? Also, I would appreciate any insight as to what would happen to any existint entities.

I have no experience with GAE but unless they do some very strange things, the canonical solution would be to use either an abstract base class inheriting from ndb.Model - if ndb supports abstract model classes - or a mixin:

class QBaseMixin(object):
    @classmethod
    def q_base(cls, ancestor):
        return cls.query(ancestor=ancestor).order(cls.codigo)


class MyModel(ndb.Model, QBaseMixin):
    # model code here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM