MongoDB,MongoEngine:如何通过其嵌入的文档获取文档?

2024-09-28 01:29:21 发布

您现在位置:Python中文网/ 问答频道 /正文

当我拥有文档对象的EmbeddedDocument对象时,如何访问它? 例如:

class ToySale(EmbeddedDocument):
    end_time = FloatField()
    percentage = IntField()

    @property
    def super_price(self):
        # I want to get access to Toy Document, something like that
        return self.toy.price - (self.percentage * self.toy.price / 100)

class Toy(Document)
    sale = EmbeddedDocumentField(ToySale)
    price = IntField()

Django-ORM有类似的“related_-name”机制,但在mongoengineorm中我没有发现类似的东西。在


Tags: to对象文档selftimedocumentpriceclass
2条回答

您可以通过EmbeddedDocument字段获取文档。在

例如,end_time

Toy.objects(sale__end_time=3.14)

percentage

^{pr2}$

双方:

Toy.objects(sale__end_time=3.14, sale__percentage=3)

如果您已经有EmbeddedDocument,例如toy_sale,您可以这样做:

Toy.objects(**{'sale__' + key: value 
               for key, value in toy_sale.to_mongo().items()
               if not key.startswith('_')})

或者只是:

Toy.objects(sale=toy_sale)

请参阅文档:http://mongoengine-odm.readthedocs.org/en/latest/guide/querying.html#filtering-queries。在

问题解决了。在

class ToySale(EmbeddedDocument):
    end_time = FloatField()
    percentage = IntField()
    uid = IntField()

    @property
    def super_price(self):
        toy = Toy.objects(sale__uid=self.uid)  # get Document by EmbeddedDocument
        return toy.price - (self.percentage * toy.price / 100)

相关问题 更多 >

    热门问题