MongoEngine: Replacing get_or_create with upsert/update_one



我知道get_or_create现在不赞成使用upsert,但我如何使update_one返回对象,而不是修改的对象数量,如果我不想更新任何内容,我可以只检索一个对象吗?

例如

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   

返回一个Model对象(如果不存在则为新对象,如果存在则为现有对象)。使用新方法的等效效果是什么?

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)

有没有办法让它返回对象,并让它的行为完全像get_or_create

我在文档

中找不到如何做到这一点

您非常接近,但您需要通过修改而不是更新命令使用findAndModify命令。

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)

注意前两个修改kwargs-upsertnew。还要注意$setOnInsert操作符的例子,它只会在findAndModify执行upstart时设置字段。

您应该看看modify。通过传递new=True,您将获得更新的对象(或者mongodb中的文档)。

最新更新