Monday 4 January 2021

Designing the Model for Nested Objects for Python Mongoengine

I am new to ORM modeling in python.

Can someone help me to design a Class model in python mongoengine.

I want this structure to be inserted into the mongo database.

{
    "_id": ObjectId("5fedb7634600c11c2f3d38df"),
    "parent": {
        "_ref": {
            "$ref": "collection_a",
            "$id": ObjectId("5cddb7634600c11c2f343adf")
        },
        "status": "active"
    },
    "children": [
        {
            "_ref": {
                "$ref": "collection_a",
                "$id": ObjectId("5cedb7634600c11c2f343adf")
            },
            "status": "active"
        },
        {
            "_ref": {
                "$ref": "collection_a",
                "$id": ObjectId("5bedb7634600c11c2f343adf")
            },
            "status": "in-active"
        }
    ]
}

I have tried with

class ParentChildReference(EmbeddedDocument):
    ref = GenericReferenceField(choices='collection_a', dbref=False, required=True)
    status= StringField(required=True)

    def __str__(self):
        return 'ref={o.ref},status={o.status}'.format(o=self)

class ParentChildTree(Document):

    parent = EmbeddedDocumentField(ParentChildReference)
    children = EmbeddedDocumentListField(ParentChildReference)

    meta = {
        'auto_create_index': True,
        'collection': 'parent_dependency_tree'
    }

    def __str__(self):
        return 'parent ={o.parent},children ={o.children}'.format(o=self)



I am getting error like The source SON object needs to be of type 'dict' upon saving the document, Please suggest me here.

Thanks in advance



from Designing the Model for Nested Objects for Python Mongoengine

No comments:

Post a Comment