[FIXED] MongoEngine: difference between EmbeddedDocumentListField() and ListField(EmbeddedDocumentField())?

Issue

title. are those two statements do the same thing, or am I missing something here?

cars = db.EmbeddedDocumentListField(Car, default= [])

vs

cars = db.ListField(db.EmbeddedDocumentField(Car), default=[])

Solution

EmbeddedDocumentListField supports querying operations like count(), filter(), delete(), create() over the list of embedded documents returned. Hence, it would be more beneficial to use EmbeddedDocumentListField() instead of List(EmbeddedDocumentField()).

For more details and the list of methods refer to:

http://docs.mongoengine.org/apireference.html#embedded-document-querying

Here is an example using methods of EmbeddedDocumentListField showing how to add an EmbeddedDocument to an EmbeddedDocumentListField 2 levels down the primary document model:

model1_obj.model2_list.get(model2_id_field=model2_id).model3_list.create(**model3_data)

or

model1_obj.model2_list.filter(model2_id_field=model2_id).first().model3_list.create(**model3_data)

Here are model and view classes related to this code snippet:

models.py:

from mongoengine import *

class Model3(EmbeddedDocument):
    field1 = StringField()
    field2 = StringField()
    field3 = StringField()

class Model2(EmbeddedDocument):
    # other fields
    model2_id_field = # Some field
    model3_list = EmbeddedDocumentListField(Model3)

class Model1(Document):
    # other fields
    model2_list = EmbeddedDocumentListField(Model2)

views.py: (Implements patch method using Django rest framework)

class Model1AddModel3(APIView):
    def get_object(self, id):
        return Model1.objects.get(pk=id)

    def patch(self, request, id, format=None):
        model1_obj = self.get_object(id)
        #
        # Validate request.data here
        # Extract model2 identifier and model3 data from request.data
        # e.g.:
        # model2_id = request.data['model2id']
        # model3_data = {'field1': 'a', 'field2': 'a', 'field3': 'a', }
        #
        model1_obj.model2_list.get(model2_id_field=model2_id).model3_list.create(**model3_data)
        #
        # You can also use:
        # model1_obj.model2_list.filter(model2_id_field=model2_id).first().model3_list.create(**model3_data)
        #
        model1_obj.save()
        return Response(some_data, status=status.HTTP_201_CREATED)


Answered By - NiKS001
Answer Checked By - Clifford M. (Python.Easybugfix Volunteer)

Related Posts

Post a Comment