Mongoengine reference another document's field

坚强是说给别人听的谎言 提交于 2020-01-15 12:31:22

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/17433971/mongoengine-reference-another-documents-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!