我在umongo中获取关系字段时遇到了一些问题。每个文档定义都在一个单独的文件中。在这个例子中,我有两个基本的实体,account和target。每个目标都有一个帐户的引用。
//account/schema.py
from datetime import datetime
from pymongo import MongoClient
from umongo import Instance, Document, fields, validate
import os
log = Config.config_logger(__name__)
mongo_url = os.environ.get('MONGO_URL')
db = MongoClient(mongo_url).mydb
instance = Instance(db)
@instance.register
class AccountSchema(Document):
user_id = fields.StringField(required=True, unique=True)
user_name = fields.StringField(required=True)
account_type = fields.StringField(required=True)
class Meta:
collection = db.account
# Make sure that unique indexes are created
AccountSchema.ensure_indexes()
try:
sub = AccountSchema(user_id='my8htwwi', account_type='SUBSCRIPTION', user_name='myuser')
sub.commit()
freeloader = AccountSchema(user_id='ouygouyg', account_type='FREE', user_name='myotheruser')
freeloader.commit()
except Exception:
log.info('account already created')
我在底部添加了一些手动数据,当我执行这个文件或将它导入其他地方时,这很好。
我为"目标"定义第二个实体架构
//目标/方案.py
from datetime import datetime
from pymongo import MongoClient
from umongo import Instance, Document, fields, validate
import os
mongo_url = os.environ.get('MONGO_URL')
db = MongoClient(mongo_url).mydb
instance = Instance(db)
@instance.register
class TargetSchema(Document):
account = fields.ReferenceField('AccountSchema', required=True)
date = fields.DateTimeField(
default=lambda: datetime.utcnow(),
allow_none=False
)
somefield = fields.IntegerField(required=True)
value = fields.IntegerField(required=True)
class Meta:
collection = db.target
# Make sure that unique indexes are created
TargetSchema.ensure_indexes()
服务.py
from models.account.schema import AccountSchema
from models.target.schema import TargetSchema
class Service:
self._odm = TargetSchema
....
def save_test(data):
account = AccountRepo().find({'user_id': self._user_id})
# account returns a valid object
item = self._odm(
account=account,
somefield=123123,
value=1234
)
return item.commit()
当我调用save_test方法时,我不断得到:
umongo.exceptions.NotRegisteredDocumentError: Unknown document class `AccountSchema`
如果我尝试在中传递类对象AccountSchema,我会得到同样的错误
from models.account.schema import AccountSchema
@instance.register
class TargetSchema(Document):
account = fields.ReferenceField(AccountSchema, required=True)
我的感觉是,这与实例化/导入实例的顺序有关,但尝试将它们四处移动,例如移动到__init__.py
中,似乎不会改变任何事情。
或者如何在每个模式定义中:
db = MongoClient(mongo_url).target
instance = Instance(db)
我能找到的所有例子都将referencefield类定义保存在同一个文件中,所以我真的不知道如何让不同的注册实例相互"了解"。
所以问题不是在同一个db实例中声明和注册所有类。
即在__init__.py
中,对于我移动的模型文件夹:
from umongo import Instance, Document, fields, validate
from pymongo import MongoClient
db = MongoClient(mongo_url).mydb
instance = Instance(db)
然后在每个模式文件中:
from models import db
from models import instance