我在让人际关系领域在umongo中工作时遇到了一些麻烦。每个文档定义都在单独的文件中。在此示例中,我有两个基本实体,即帐户和目标。每个目标都有对帐户的引用。
// 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')
我在底部添加了一些手动数据,当我执行此文件或将其导入其他地方时,该数据可以正常工作。
我为“目标”定义了第二个实体模式
// target / schema.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()
service.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类定义保留在同一文件中,因此我不确定如何使不同的注册实例相互“了解”。
所以问题不是在声明所有类并将其注册到同一数据库实例。
即在我移动的models文件夹的__init__.py
中:
from umongo import Instance, Document, fields, validate
from pymongo import MongoClient
db = MongoClient(mongo_url).bigbox
instance = Instance(db)
然后在每个模式文件中:
from models import db
from models import instance