【问题标题】:MongoEngine: Replacing get_or_create with upsert/update_oneMongoEngine:用 upsert/update_one 替换 get_or_create
【发布时间】:2014-09-15 10:55:30
【问题描述】:

我知道 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.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 完全一样?

我在documentation 中找不到如何执行此操作

【问题讨论】:

    标签: django mongoengine


    【解决方案1】:

    您非常接近,但您需要通过modify 使用 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)
    

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

    【讨论】:

    • 感谢您的回答。但是你知道我为什么会收到'QuerySet' object has no attribute 'modify'吗?
    • 哦,modify 命令似乎从 0.9 开始可用,但最新的 pip 版本似乎是 0.8.7
    • 你必须通过 pip 从 master 安装。见:stackoverflow.com/questions/20101834/…
    • @Ross 所以要确定它是否是新文档,我必须为此目的创建 newUser 字段吗?看起来像一个丑陋的黑客,还是有更好的方法?
    【解决方案2】:

    您应该查看modify。传递 new=True 您将获得更新的对象(或文档,用 mongodb 的说法)。

    【讨论】:

      猜你喜欢
      • 2014-09-04
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2019-07-09
      • 1970-01-01
      • 2021-07-10
      相关资源
      最近更新 更多