标题。这两个陈述是做同样的事情,还是我在这里遗漏了什么?
cars = db.EmbeddedDocumentListField(Car, default= [])
VS
cars = db.ListField(db.EmbeddedDocumentField(Car), default=[])
答案 0 :(得分:3)
EmbeddedDocumentListField支持在返回的嵌入文档列表中查询count(),filter(),delete(),create()等操作。因此,使用EmbeddedDocumentListField()而不是List(EmbeddedDocumentField())会更有利。
有关详细信息和方法列表,请参阅:
http://docs.mongoengine.org/apireference.html#embedded-document-querying
==编辑:更多详情==
以下是使用EmbeddedDocumentListField方法的示例,其中显示了如何将EmbeddedDocument添加到主文档模型中的EmbeddedDocumentListField 2级别:
model1_obj.model2_list.get(model2_id_field=model2_id).model3_list.create(**model3_data)
或
model1_obj.model2_list.filter(model2_id_field=model2_id).first().model3_list.create(**model3_data)
以下是与此代码段相关的模型和视图类:
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 :(使用Django rest框架实现补丁方法)
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)