我正在使用Python 3.6,Flask和Mongoengine构建一个Web应用程序,该应用程序中有2个类。
class PayMethods(BaseDocument):
name = StringField(required=True, max_length=200, unique=True)
class Expense(BaseDocument):
amount = IntField()
descreption = StringField(required=True, max_length=200)
pay_method = ReferenceField(PayMethods, required=True)
我正在尝试在PayMethods
和Expense
之间建立一对多关系
(Expense
应该只有1个PayMethod
,而只有1个PayMethod
可以与许多Expenses
相关。)
我注意到我可以使用无效的Expense
创建一个新的PayMethod
文档,这意味着一个表示PayMethod
的JSON在数据库中尚不存在。
这怎么可能?数据库为何不强制执行这种关系并且不允许执行此操作?
这是我尝试做的,新的对象数据:
z = {'amount': 200, 'description': 'Random stuff', 'pay_method': ObjectId('5b7859092c88840c33a0a5b8'), 'timestamp': 'Sun, 19 Aug 2018 16:10:41 GMT'}
没有PayMethod
和ID 5b7859092c88840c33a0a5b8
将新对象保存到数据库:
Expense(**z).save()
<Expense: Expense object>
在尝试访问文档PayMethod
时:
c.pay_method
Traceback (most recent call last):
File "/Users/shlomilanton/workscpace/slots_tracker_server/venv/lib/python3.6/site-packages/IPython/core/interactiveshell.py", line 2961, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-16-1150ff374ac6>", line 1, in <module>
c.pay_method
File "/Users/shlomilanton/workscpace/slots_tracker_server/venv/lib/python3.6/site-packages/mongoengine/fields.py", line 1076, in __get__
raise DoesNotExist('Trying to dereference unknown document %s' % value)
mongoengine.errors.DoesNotExist: Trying to dereference unknown document DBRef('pay_methods', ObjectId('5b7859092c88840c33a0a5b8'))
我做错了什么?