woh*_*ejm 2 django mongodb mongoengine
我一直在 Django 应用程序中使用 MongoEngine 的 get_or_create 方法。今天,我注意到有一些重复的条目。我在 MongoEngine API Reference for get_or_create 中发现了这一点:
\n\n\n\n\n这需要两个单独的操作,因此存在竞争条件。由于 mongoDB 中没有事务,因此应研究其他方法,以确保使用此方法时不会意外重复数据。现在计划在 1.0 之前删除
\n
我应该使用这样的东西吗?:
\n\nfrom models import Post\npost = Post(name=\'hello\')\ntry:\n Posts.objects.get(name=post.name)\n print "exists"\nexcept:\n post.save()\n print "saved"\nRun Code Online (Sandbox Code Playgroud)\n\n这能解决我的问题吗?\n有更好的方法吗?
\n要执行更新插入,请使用以下语法:
Posts.objects(name="hello").update(set__X=Y, upsert=True)
Run Code Online (Sandbox Code Playgroud)
这将添加一个名为“hello”的帖子,如果它尚不存在,则 X = Y,否则它将更新一个现有帖子,只需设置 X = Y。
| 归档时间: |
|
| 查看次数: |
4387 次 |
| 最近记录: |