2

我很难将我的模型从带有 MySQL 的标准 Django orm 迁移到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()

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

4

2 回答 2

2

您在定义类方法时犯了一个错误preSave。您正在尝试hierarchy ListFieldPlace类(而不是实例)中获取 len。这是因为您使用的是方法的第一个参数 - 它不是实例,而是类本身。请改用第三个参数:

@classmethod
def preSave(cls, sender, document, **kwargs):
    document.hierarchy_size = len(document.hierarchy)
于 2013-08-12T14:21:42.647 回答
0

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

于 2020-11-29T05:12:23.867 回答