{"id":956,"date":"2015-11-27T21:19:51","date_gmt":"2015-11-27T21:19:51","guid":{"rendered":"https:\/\/fir3netwp.gmsrrpobkbd.com\/2015\/11\/27\/django-mongoengine-how-to-perform-an-update-or-create-action\/"},"modified":"2023-01-06T16:39:01","modified_gmt":"2023-01-06T16:39:01","slug":"django-mongoengine-how-to-perform-an-update-or-create-action","status":"publish","type":"post","link":"https:\/\/www.fir3net.com\/Web-Development\/Django\/django-mongoengine-how-to-perform-an-update-or-create-action.html","title":{"rendered":"Django+MongoEngine Update_or_Create Action"},"content":{"rendered":"

BuiltIn ORM<\/h2>\n

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

update_or_create(defaults=None, **kwargs)<\/pre>\n

However MongoEngine replaces the builtin object-relational mapper (ORM). Because of this an alternative is required.<\/p>\n

MongoEngine<\/h2>\n

Within MongoEngine the modify<\/span> method can be used to achieve the same goal. Lets look at an example. First of all below is our example model,<\/p>\n

class Fruit(mongoengine.Document): \r\n    number = mongoengine.StringField(max_length=50, unique=True) \r\n    color = mongoengine.StringField(max_length=50) \r\n    size = mongoengine.StringField(max_length=50)<\/pre>\n

And now lets look at the modify<\/span> command.<\/p>\n

Fruit.objects(number='12345').modify(upsert=True, new=True, \r\n                                     set__color='green',\r\n                                     set__size='small')<\/pre>\n

The 2 main parameters are,<\/p>\n