Mongoengine引用另一个文档的字段 [英] Mongoengine reference another document's field

查看:464
本文介绍了Mongoengine引用另一个文档的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以这样做吗?

  class Doc1:
fieldd1 = StringField()

class Doc2:
fieldd2 = ReferenceField(Doc1.fieldd1)

或者我应该参考文档,然后在需要时获取字段信息

解决方案

这不是可以的,它是引用文件。要获得 fieldd1 ,您必须执行以下操作:

  class Doc1(Document): 
fieldd1 = StringField()

class Doc2(Document):
fieldd2 = ReferenceField(Doc1)

Doc2.objects.first()。fieldd2 .fieldd1

如果您只想将文档包含在另一个文档中,那么请查看 EmbeddedDocument EmbeddedDcoumentField

  class Doc1(EmbeddedDocument):
fieldd1 = StringField()

class Doc2(Document):
fieldd2 = EmbeddedDcoumentField(Doc1)

Doc2。 object.first()。fieldd2.fieldd1

但是你总是可以设置自己的属性:

  class Doc1(Document):
fieldd1 = StringField()

class Doc2(Document) b $ b fieldd2 = ReferenceField(Doc1)

@property
def fieldd1(self):
return self.fieldd2.fieldd1

Doc2.objects 。第一( ).fieldd1

请参阅文档: https://mongoengine-odm.readthedocs.org/en/latest/guide/defining-documents.html 。 p>

Is it possible to do something like this?

class Doc1:
    fieldd1 = StringField()

class Doc2:
    fieldd2 = ReferenceField(Doc1.fieldd1)

Or should I just reference the Doc and then get the field information whenever I need it

解决方案

This not posible and it is reference to document. To get fieldd1 you must do:

class Doc1(Document):
    fieldd1 = StringField()

class Doc2(Document):
    fieldd2 = ReferenceField(Doc1)

Doc2.objects.first().fieldd2.fieldd1

If you want just include document to another as part of one document then look at EmbeddedDocument and EmbeddedDcoumentField:

class Doc1(EmbeddedDocument):
    fieldd1 = StringField()

class Doc2(Document):
    fieldd2 = EmbeddedDcoumentField(Doc1)

Doc2.objects.first().fieldd2.fieldd1

But you always can set own properties:

class Doc1(Document):
    fieldd1 = StringField()

class Doc2(Document):
    fieldd2 = ReferenceField(Doc1)

    @property
    def fieldd1(self):
        return self.fieldd2.fieldd1

Doc2.objects.first().fieldd1

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

这篇关于Mongoengine引用另一个文档的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆