I just switched from SQL to MongoDB. When I was changing all my model fields from Django fields to MongoEngine fields, I realized there was no AutoField()
. Does anyone know a substitute for this?
CodePudding user response:
You can use ObjectIdField
of mongodb like this:
from bson import ObjectId
from mongoengine import Document, ObjectIdField
class ModelName(Document):
id = ObjectIdField(primary_key=True, default=ObjectId)
and create your object in the model like this:
obj_doc = ModelName.objects.create(field1='value1', field2='value2')
then if want to check id of your object:
print(obj_doc.id)
here id
of obj_doc
will be created automatically.