Reputation: 682
My document has some EmbeddedDocumentList and each of EmbeddedDocument should have autogenerated ObjectId(like _id) field because I will write query to get single EmbeddedDocument with this _id field.
How to reach that?
Upvotes: 10
Views: 7716
Reputation: 682
Basically you can do it with following code
from mongoengine import *
from bson.objectid import ObjectId
class MyEmbeddedDocument(EmbeddedDocument):
oid = ObjectIdField(required=True, default=ObjectId,
unique=True, primary_key=True)
...
class MyDocument(Document):
embedded_list = EmbeddedDocumentListField(MyEmbeddedDocument)
...
Let explain more,
According to documentation you can add ObjectIdField to your models however it is not required and primary_key then you should set this attribute as True. Also, it do not generate ObjectId for each of it then import and set default it as ObjectId.
Last step is little bit tricky. If it is required explain,
bson.objectid.ObjectId is class that generate new objectids.
Moreover documentation say that default value can be callable than that explain clearly how it is work.
Also name of _id for embeddeddocument is not best naming practise beacuse you will write query for embeddeddocument with duble underscore and '_id' name have one more underscore as following code
MyDocument.objects.get(notice___id)
Then mongoengine throws exception beacuse of '_id' name have one more underscore. Thus you should give name as 'oid' as a short version of objectId or renname 'id' directly or what you want.
Upvotes: 12