0

i am trying to make a mongodb database , the code bellow has some of the database documents, i am trying to divide the models into two parts, a part on a common/models.py file where i put the abstract classes, the other part is on monitor/models.py where i add some class methods:

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 (the class methods are not important for this question):

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

Now when i try fetching the list of devices for a topology after creating some instances :

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

I receive this error:

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

the error does not occur when the code is not divided

bagerard
  • 5,681
  • 3
  • 24
  • 48
A.Mahamedi
  • 353
  • 1
  • 2
  • 11

1 Answers1

0

There are some internals of mongoengine that rely on the model class names to be unique, try using different name for the concrete class (avoid class device(device): and class topology(topology):)

EDIT: I was able to reproduce your issue. On my end, I could make it work by specifying allow_inheritance in meta = {'abstract': True, 'allow_inheritance': True} in both of your abstract classes

bagerard
  • 5,681
  • 3
  • 24
  • 48