Clone a MongoEngine object (Python MongoDB layer)

Now, imagine you have something like:

class Company(Document):
    name            = StringField(required=True)
    company_id      = StringField(required=True)
    phone           = StringField()

For some reason, you want to clone this object on the DB. That’s is, you want to create another exact object in the DB without the need to create another object manually an copy all it’s attributes. You can do it if you add the following method (a real hack, because MongoEngine doesn’t support cloning objects):

def clone(self):
        del self.__dict__['_id']
        del self.__dict__['_created']
        del self.__dict__['_changed_fields']
        self.id = ObjectId()

Note: If you have a SequenceField() you will need to delete it too so it can step up when you save the new object.

Don’t forget to:

from bson import ObjectId

So you can do:

obj = Company.objects(name='MyCompany')
obj.clone()
obj.name = 'MyOtherCompany'
obj.save()

Really useful, specially if your object has 8+ fields and one of more of it’s fields is a EmbeddedDocument.

Kind regards

Etiquetado , ,

Deja un comentario