Django provides a convenient method when needing to update a model instance, but create if it does not exist. The method is shown below,
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, 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
Latest posts by Rick Donato (see all)
- How to Configure a BIND Server on Ubuntu - March 15, 2018
- What is a BGP Confederation? - March 6, 2018
- Cisco – What is BGP ORF (Outbound Route Filtering)? - March 5, 2018
Want to become a Django expert?
Here is our hand-picked selection of the best courses you can find online:
The Complete Web Development Bootcamp course
Django Practical Guide course
Django Full Stack Developer Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial