class Parent(document):
name = StringField()
children = ListField(ReferenceField('Child'))
class Child(document):
name = StringField()
parents = ListField(ReferenceField(Parent))
@app.route('/home/')
def home():
parents = Parent.objects.all()
return render_template('home.html', items=parents)
我有两个与上面类似的集合,它们保持多对多关系。
在带有 Angular 的模板中,我将一个 javascript 变量设置为父母列表,如下所示:
$scope.items = {{ parents|tojson }};
这会产生一个父数组,它们chilren
是一个对象 ID(引用)数组,而不是取消引用的child
对象:
$scope.items = [{'$oid': '123', 'name': 'foo', 'children': [{'$oid': '456'}]}];
我希望这个角度对象包含所有取消引用的子对象。有没有一种有效的方法来做到这一点?
到目前为止,这是唯一适合我的方法,时间为 O(n^3)。为了清楚起见,我已经最小化了列表理解。多个obj['_id'] = {'$oid': str(obj['_id']}
是必要的,以将其转换为ObjectId
可以序列化为 json 的东西。
@app.route('/home/')
def home():
parents = Parent.objects.all()
temps = []
for parent in parents:
p = parent.to_mongo()
# At this point, the children of parent and p are references only
p['_id'] = {'$oid': str(p['_id'])
temp_children = []
for child in parent.children:
# Now the child is dereferenced
c = child.to_mongo()
c['_id'] = {$oid': str(c['_id'])}
# Children have links back to Parent. Keep these as references.
c['parents'] = [{'oid': str(parent_ref)} for parent_ref in c['parents']]
temp_children.append(c)
p['children'] = temp_children
temps.append(parent.to_mongo())
return render_template('home.html', items=temps)
以下内容不起作用,但会导致未取消引用的子项:
json.loads(json.dumps(accounts))