我正在尝试构建一种“迷你 django 模型”,以便在不使用 norel Django 的 dist 的情况下使用 Django 和 MongoDB(我不需要这些...的 ORM 访问权限)。
所以,我正在尝试做的是模仿 django 默认模型的标准行为或“实现”......这就是我到目前为止所拥有的:
文件“models.py”(基础)
from django.conf import settings
import pymongo
class Model(object):
@classmethod
def db(cls):
db = pymongo.Connection(settings.MONGODB_CONF['host'], settings.MONGODB_CONF['port'])
@classmethod
class objects(object):
@classmethod
def all(cls):
db = Model.db() #Not using yet... not even sure if that's the best way to do it
print Model.collection
文件“mongomodels.py”(实现)
from mongodb import models
class ModelTest1(models.Model):
database = 'mymongodb'
collection = 'mymongocollection1'
class ModelTest2(models.Model):
database = 'mymongodb'
collection = 'mymongocollection2'
文件“views.py”( View )
from mongomodels import ModelTest1, ModelTest2
print ModelTest1.objects.all() #Should print 'mymongocollection1'
print ModelTest2.objects.all() #Should print 'mymongocollection2'
问题是它不是从 ModelTest1 访问变量,而是从原始模型访问变量...怎么了??
最佳答案
您必须为 objects
提供某种指向包含它的类的链接。目前,您只是对其进行硬编码以使用 Model()
的属性。因为您没有实例化这些类,所以您将不得不使用装饰器或元类在 Model()
的每个子类中为您创建 object
类。
关于Python - 在调用类方法时从父类访问子类的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13279510/