0

当我拥有 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 中我没有找到类似的东西。

4

2 回答 2

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

于 2013-10-10T07:32:53.307 回答
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)
于 2013-10-10T11:02:57.063 回答