MongoEngine:用upsert/update_one替换get_or_create

con*_*d00 2 django mongoengine

我知道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   
Run Code Online (Sandbox Code Playgroud)

返回一个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)
Run Code Online (Sandbox Code Playgroud)

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

我在文档中找不到如何做到这一点

Ros*_*oss 10

您非常接近,但您需要通过修改而不是更新命令来使用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)
Run Code Online (Sandbox Code Playgroud)

记下前两个修改kwargs - upsertnew.另请注意$ setOnInsert运算符示例,该示例仅在findAndModify执行upsert时才设置字段.