Django+MongoEngine - How to Perform an Update_or_Create Action

BuiltIn ORM

Django provides a convenient method when needing to update a model instance, but create if it does not exist. The method is shown below,

update_or_create(defaults=None, **kwargs)

However MongoEngine replaces the builtin object-relational mapper (ORM). Because of this an alternative is required.


Within MongoEngine the modify method can be used to achieve the same goal. Lets look at an example. First of all below is our example model,

class Fruit(mongoengine.Document): 
    number = mongoengine.StringField(max_length=50, unique=True) 
    color = mongoengine.StringField(max_length=50) 
    size = mongoengine.StringField(max_length=50)

And now lets look at the modify command. 

Fruit.objects(number='12345').modify(upsert=True, new=True, 

The 2 main parameters are,

  • upsert – insert if document doesn't exist
  • new – return updated rather than original document


Tags: Python, Django