MongoEngine: Replacing get_or_create with upsert/update_one

隐身守侯 提交于 2019-12-07 22:24:25

问题


I understand that get_or_create is now deprecated in favour of using upsert, but how do I make update_one to return the object rather the number of objects modified, and can I just retrieve an object if I don't want to update anything?

e.g.

Model.objects.get_or_create(first_name='John', last_name='Potter', age=40)
# assuming that first_name + last_name + age are enough to uniquiely indentify a person   

returns a Model object (a new object if it didn't exist, and existing object if it does). What would be the equivalent of this using the new method?

Model.objects(first_name='John', last_name='Potter', age=40).update_one(upsert=True)
# returns number of objects (1)
Model.objects(first_name='John', last_name='Potter', age=40).update_one(set__first_name='John', set__last_name='Potter', set__age=40,upsert=True)
# returns number of objects (1)

Is there a way to make it return the object, and make it behave exactly like get_or_create?

I couldn't find how to do this in the documentation


回答1:


You are very close but you need to use a findAndModify command via modify rather than an update command.

NewDoc = Model.objects(first_name='John', 
                       last_name='Potter', 
                       age=40).modify(upsert=True, new=True,
                                      set__first_name='John, 
                                      set__last_name='Potter', 
                                      set__age=40,
                                      set_on_insert__newUser=True)

Take note of the first 2 modify kwargs - upsert and new. Also take note of the $setOnInsert operator example which will only set a field if the findAndModify does an upsert.




回答2:


You should look at modify. Passing a new=True you'll get the updated object (or document, in mongodb parlance).



来源:https://stackoverflow.com/questions/25846462/mongoengine-replacing-get-or-create-with-upsert-update-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!