MongoDB,MongoEngine:如何通过EmbeddedDocument获取Document?

时间:2013-10-10 04:18:13

标签: python mongodb pymongo mongoengine

当我拥有EmbeddedDocument对象时,如何访问Document对象? 例如:

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'机制,但是在mongoengine ORM中我没有找到这样的东西。

2 个答案:

答案 0 :(得分:2)

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

例如end_time

Toy.objects(sale__end_time=3.14)

percentage

Toy.objects(sale__percentage=3)

两者:

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

答案 1 :(得分:0)

问题解决了。

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)