ListField(ReferenceField(x))查询mongoengine

时间:2019-06-24 22:17:07

标签: python mongoengine

我试图建立一个mongodb数据库,下面的代码有一些数据库文档,我试图将模型分为两部分,一部分放在common / models.py文件中,我将抽象类放在其中,另一部分在monitor / models.py上,其中添加了一些类方法:

common.py:

class device(DynamicDocument):
    hostname = StringField(required=True)
    management = EmbeddedDocumentField(access)
    interfaces = ListField(ReferenceField(interface))
    loopback_addr = StringField()

    meta = {'abstract': True}



class topology(DynamicDocument):
    topology_name = StringField(required=True)
    topology_desc = StringField(required=False)
    devices = ListField(ReferenceField(device))
    links = ListField(ReferenceField(link))

    meta = {'abstract' : True}

monitor.py(此问题的类方法并不重要):

from mongoengine import *
from common.models import *

class device(device):

  def connect(self):
    driver = get_network_driver("ios")
    device = None
    try:
        device =  driver(self.management.management_address,self.management.username,
                        self.management.password)
        device.open()
    except Exception as e:
        print(e)
    return device


class topology(topology):

    def do_things(self)

         pass

现在,当我尝试在创建一些实例后为拓扑获取设备列表时:

mongoengine.connect("testdb",host = "0.0.0.0", port = 27017)
topology_ins = topology.objects()[0]
for dev in topology_ins.devices:
    print(dev.hostname)

我收到此错误:

Traceback (most recent call last):
 File "models.py", line 45, in <module>
 for dev in topology_ins.devices:
  File "/usr/lib/python3.7/site-packages/mongoengine/fields.py", line 852, in _get_
return super(ListField, self).__get__(instance, owner)
  File "/usr/lib/python3.7/site-packages/mongoengine/base/fields.py", line 282, in _get_
name=self.name
  File "/usr/lib/python3.7/site-packages/mongoengine/dereference.py", line 92, in _call_
self.object_map = self._fetch_objects(doc_type=doc_type)
  File "/usr/lib/python3.7/site-packages/mongoengine/dereference.py", line 174, in _fetch_objects
object_map[(collection, doc.id)] = doc
AttributeError: 'device' object has no attribute 'id

不对代码进行分割时不会发生错误

1 个答案:

答案 0 :(得分:0)

mongoengine的某些内部结构依赖于模型类名称的唯一性,请为具体类尝试使用其他名称(避免使用class device(device):class topology(topology):

编辑: 我能够重现您的问题。最后,我可以通过在两个抽象类的allow_inheritance中指定meta = {'abstract': True, 'allow_inheritance': True}来使其工作