python - Implementing Bi-Directional relationships in MongoEngine -
i'm building django application uses mongodb , mongoengine store data. present simplified version of problem, want have 2 classes: user , page. each page should associate user , each user page.
from mongoengine import * class page(document): pass class user(document): name = stringfield() page = referencefield(page) class page(document): content = stringfield() user = referencefield(user)
(note page must defined before user. if missing pythonic way handle circular dependencies, let me know.) each document can created , saved fine, assigning page user throws error.
u = user(name='jeff') u.save() p = page(content="i'm page!") p.save() p.user = u p.save() u.page = p u.save() traceback (most recent call last): file "<stdin>", line 1, in <module> file "build\bdist.win32\egg\mongoengine\document.py", line 71, in save file "build\bdist.win32\egg\mongoengine\base.py", line 303, in validate mongoengine.base.validationerror: invalid value field of type "referencefield"
can explain why exception being thrown, doing wrong, , how can avoid it?
this proper solution:
from mongoengine import * class user(document): name = stringfield() page = referencefield('page') class page(document): content = stringfield() user = referencefield(user)
use single quotes ('page') denote classes have not yet been defined.
Comments
Post a Comment