使用ModelMixin来重用模型

标签:Google App Engine, Python

由于PolyModel比Model有更多的存储空间开销,对于斤斤计较的程序员来说,有时候会不想使用它。但是这样一来就没法重用了,而《Reusing models with ModelMixin》这篇文章则介绍了解决办法。

简单来说,不能重用的原因是__metaclass__不一致,所以只要自己再创建一个ModelMixin类用来继承即可:
class ModelMixin(object):
    __metaclass__ = db.PropertiedClass

    @classmethod
    def kind(self):
        """Need to implement this because it is called by PropertiedClass
        to register the kind name in _kind_map. We just return a dummy name.
        """
        return '__model_mixin__'
接下来就是继承和复用了:
class DateMixin(ModelMixin):
    created = db.DateTimeProperty(auto_now_add=True)
    updated = db.DateTimeProperty(auto_now=True)

class AuditMixin(ModelMixin):
    created_by = db.UserProperty()
    updated_by = db.UserProperty()

class Account(db.Model, DateMixin, AuditMixin):
    name = db.StringProperty()

class SupportTicket(db.Model, DateMixin, AuditMixin):
    title = db.StringProperty()

class Item(db.Model, DateMixin):
    name = db.StringProperty()
    description = db.StringProperty()

0条评论 你不来一发么↓

    想说点什么呢?