让我们考虑一下我有一些模型类:
class UserModel(Model):
title = StringType()
class ItemModel(Model):
...
这里的模型只是一个验证器(示意图)。但是我有一个数据库(MongoDB),我想向模型添加一些操作。
class CRUDOperations(object):
def get(self):
return "Get Method"
我想以某种方式将 CRUDOperations “插入”到模型中,并希望它可以像: 一样被访问UserModel.crud.get()
,即不创建实例。我试图这样做但失败了,这有一个常见的做法吗?
from schematics.models import Model
from schematics.types import StringType
class CRUDOperations(object):
def __init__(self, model_cls):
# Upd. i need access to model_cls to get
# some class attributes like collection name, database name etc.
self.model_cls = model_cls
@classmethod
def get_crud(cls, model_cls):
cls.model_cls = model_cls
return cls
@classmethod
def get(cls, oid=None):
# and if i'll use mongo here i'll need to access pymongo driver
# like this: cls.model_cls._col_.find_one({"_id": oid})
return 'test ok! {}'.format(cls.model_cls)
class CRUDModel(Model):
__crud__ = None
def __init__(self, *args, **kwargs):
super(CRUDModel, self).__init__(*args, **kwargs)
print "CRUDModel.__init__"
self.__crud__ = CRUDOperations(self).get_crud()
@classmethod
def crud(cls):
if cls.__crud__ is None:
cls.__crud__ = CRUDOperations.get_crud(cls)
return cls.__crud__
class TestModel(CRUDModel):
title = StringType()
def main():
print TestModel.crud
print TestModel.crud.get()
if __name__ == '__main__':
main()
是的,我知道有很多错误,但我尝试了很多方法,所以它只是显示我拥有什么以及我需要做什么的代码(调用像 TestModel.crud.create({...}) 这样的模型的 crud 操作)