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'] = 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() = 'MyOtherCompany'

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

Kind regards

Etiquetado , ,


Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de

Estás comentando usando tu cuenta de Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )


Conectando a %s

A %d blogueros les gusta esto: