使用 Mongoengine 进行插入只能从 shell 工作,但不能从 Django 视图工作
我遇到了奇怪的情况 - 从 Django shell 创建一些 Mongoengine 对象是成功的,但是从 Django 视图创建相同的对象看起来很成功,但 MongoDB 中没有出现任何数据。即,类似的代码 -
from myapp.mongomodels import MyModel
m = MyModel(a=1, b=2, c=3)
m.save()
从 manage.py shell
运行时生成插入 MongoDB 的新对象,而从 Django 视图运行时不生成任何内容。我跟踪了代码,发现 mongoengine.Document.save() 方法运行正确,没有任何异常。
看来我错过了一些明显的事情。
将不胜感激任何帮助。
I am having strange situation - creating some Mongoengine object from Django shell is successful, but creating the same object from Django view looks like successful but without any data appeared in MongoDB. I.e. the same code like that -
from myapp.mongomodels import MyModel
m = MyModel(a=1, b=2, c=3)
m.save()
produces new object inserted into MongoDB when running from manage.py shell
, and produces nothing when running from Django view. I have traced the code and I am seeing mongoengine.Document.save()
method is running correctly without any exceptions.
Looks like I've missed something obvious.
Will be grateful for any help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够做到这一点,但使用以下命令强制保存:
You should be able to do that but force the save using:
正如我之前所说,问题在于我在保存之前分配了主键值。
我有一个系统,一些数据存储在MySQL中,一些相应的数据存储在MongoDB中。首先创建 MySQL 记录,然后再创建相关的 MongoDB 记录,并且主键值相同。因此,pymongo认为这是更新请求而不是插入请求,并且根本没有插入任何记录。
As I've told before, the problem was in that I am assigning a primary key value BEFORE saving.
I have a system with some data stored in MySQL and some corresponding data stored in MongoDB. MySQL record is created first, related MongoDB record is created right after MySQL record, with the same primary key value. Thus, pymongo thinks thas this is update request instead of insert request, and no record is inserted at all.