Jared Joke
Jared Joke

Reputation: 1356

Mongoengine reference another document's field

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

Upvotes: 1

Views: 2871

Answers (1)

tbicr
tbicr

Reputation: 26070

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.

Upvotes: 7

Related Questions