本文介绍了mongoengine中EmbeddedDocumentField和ReferenceField之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这两个领域之间有什么区别?这些字段在mongo中映射到什么样的模式?此外,关系文件应如何添加到这些字段?例如,如果我使用mongoengine import中的

  

class User(Document):
name = StringField()

类注释(EmbeddedDocument):
text = StringField()
tag = StringField()

class Post文件):
title = StringField()
author = ReferenceField(User)
comments = ListField(EmbeddedDocumentField(Comment))

并调用

 >>> some_author = User.objects.get(name =ExampleUserName)
>>> post = Post.objects.get(author = some_author)
>>> post.comments
[]
>>> comment = Comment(text =cool post,tag =django)
>>> comment.save()
>>>

我应该使用post.comments.append(comment)还是post.comments + =评论来追加这个文件?我的原始问题源自于我应该如何处理这个混乱。

解决方案

EmbeddedDocumentField 只是像 DictField 这样的父文档的路径,并存储在mongo中的父文档的一个记录中。



要保存 EmbeddedDocument 只需保存父文档。

 >> > some_author = User.objects.get(name =ExampleUserName)
>>> post = Post.objects.get(author = some_author)
>>> post.comments
[]
>>> comment = Comment(text =cool post,tag =django)
>>> post.comment.append(comment)
>>> post.save()

>>> post.comment
[<注释对象__unicode __>]

>>> Post.objects.get(author = some_author).comment
[< Comment object __unicode __>]

请参阅文档:。


Internally, what are the differences between these two fields? What kind of schema do these fields map to in mongo? Also, how should documents with relations be added to these fields? For example, if I use

from mongoengine import *

class User(Document):
    name = StringField()

class Comment(EmbeddedDocument):
    text = StringField()
    tag  = StringField()

class Post(Document):
    title    = StringField()
    author   = ReferenceField(User)
    comments = ListField(EmbeddedDocumentField(Comment)) 

and call

>>> some_author = User.objects.get(name="ExampleUserName")
>>> post = Post.objects.get(author=some_author)
>>> post.comments
[]
>>> comment = Comment(text="cool post", tag="django")
>>> comment.save()
>>> 

should I use post.comments.append(comment) or post.comments += comment for appending this document? My original question stems from this confusion as to how I should handle this.

解决方案

EmbeddedDocumentField is just path of parent document like DictField and stored in one record with parent document in mongo.

To save EmbeddedDocument just save parent document.

>>> some_author = User.objects.get(name="ExampleUserName")
>>> post = Post.objects.get(author=some_author)
>>> post.comments
[]
>>> comment = Comment(text="cool post", tag="django")
>>> post.comment.append(comment)
>>> post.save()

>>> post.comment
[<Comment object __unicode__>]

>>> Post.objects.get(author=some_author).comment
[<Comment object __unicode__>]

See documentation: https://mongoengine-odm.readthedocs.org/en/latest/guide/defining-documents.html#embedded-documents.

这篇关于mongoengine中EmbeddedDocumentField和ReferenceField之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 09:02