计算mongoengine ListField元素

时间:2013-08-12 14:13:42

标签: django django-models mongoengine

我很难将我的模型从标准Django orm与MySQL迁移到 mongoengine-odm

我有以下模型在旧结构中正常工作:

class Place(Document):

    name    = StringField()
    acronym = StringField()

    parent = ReferenceField('self')
    hierarchy = ListField(ReferenceField('self'))
    hierarchy_size = IntField()

    @classmethod
    def preSave(instance, sender, **kwargs):
        instance.hierarchy_size = len(instance.hierarchy)

signals.pre_save.connect(Place.preSave, sender=Place)

但是当使用新的mongoengine时,我面临着以前所未有的方式访问对象层次结构大小的问题。接收:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/awesome_user/workspace/awesome_project/project/models.py", line 728, in importPlacesFromMySQL
    myCountry.save()
  File "/Users/awesome_user/workspace/awesome_project/site_env/lib/python2.7/site-packages/mongoengine/document.py", line 220, in save
    signals.pre_save.send(self.__class__, document=self)
  File "/Users/awesome_user/workspace/awesome_project/site_env/lib/python2.7/site-packages/blinker/base.py", line 267, in send
    for receiver in self.receivers_for(sender)]
  File "/Users/awesome_user/workspace/awesome_project/project/models.py", line 804, in preSave
    instance.hierarchy_size = len(instance.hierarchy)
TypeError: object of type 'ListField' has no len()

是否有人知道如何访问实例的属性,例如我的长度

2 个答案:

答案 0 :(得分:1)

定义preSave classmethod时出错。您正试图从hierarchy类(非实例)中取ListField Place来获取len。这是因为你正在使用方法的第一个参数 - 它不是一个实例,它本身就是一个类。改为使用第三个参数:

@classmethod
def preSave(cls, sender, document, **kwargs):
    document.hierarchy_size = len(document.hierarchy)

答案 1 :(得分:0)

len(object.field)将检索所有子文档,然后计数。如果您只需要数组的长度而不需要检索所有文档,则可以使用len(object.to_mongo()["field"])