fir3net
PPS-Firenetbanner-780.5x190-30-03-17

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.

MongoEngine

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, 
                                     set__color='green',
                                     set__size='small')

The 2 main parameters are,

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

Links

http://mongoengine-odm.readthedocs.org/en/latest/apireference.html#mongoengine.queryset.QuerySet.modify 

Tags: Python, Django

About the Author

RDonato

R Donato

Rick Donato is the Founder and Chief Editor of Fir3net.com. He currently works as a Principal Network Security Engineer and has a keen interest in automation and the cloud.

You can find Rick on Twitter @f3lix001