MongoDB E11000 duplicate key error index when creating saving a mongoengine ReferenceField(D BRef)

2024-10-01 11:23:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在我的测试运行中从json文件加载测试fixture(以匹配Django中使用的类似fixture加载样式)。这是我目前掌握的密码

from django.utils import simplejson as json
from mongoengine import base as mongobase
from mongoengine import connect
from pymongo import json_util

db = connect("DATABASENAME")

# Clear out the current collections.
for collection in db.collection_names():
    if collection == 'system.indexes':
        continue
    db.drop_collection(collection)


# Open json fixtures

f = open('path/to/test_fixtures.json', 'r')
datas = json.loads(f.read(), object_hook=json_util.object_hook)

# For each serialised model instance, loop through and save to the database.

for data in datas:

    print data

    if data['_cls'] not in mongobase._document_registry:
        print "Skipping %s" % data['_cls2']
        continue

    model = mongobase._document_registry[data['_cls']]
    model_instance = model._from_son(data)
    model_instance.save(force_insert=True)

但是,当其中一个模型有一个ReferenceField时,它就失败了。抱怨钥匙重复。您会注意到其中有一个print语句来显示dict的内容,在一个示例运行中,我将得到以下输出,在出现错误之前这些输出看起来都很好

^{pr2}$

最后,错误是:

Traceback (most recent call last):
  File "/home/vagrant/.virtualenvs/engineclub/lib/python2.6/site-packages/django/test/testcases.py", line 292, in __call__
    self._pre_setup()
  File "/home/vagrant/.virtualenvs/engineclub/lib/python2.6/site-packages/django/test/testcases.py", line 259, in _pre_setup
    self._fixture_setup()
  File "/vagrant/engineclub/engineclub/apps/notifications/tests.py", line 67, in _fixture_setup
    model_instance.save(force_insert=True)
  File "/home/vagrant/.virtualenvs/engineclub/lib/python2.6/site-packages/mongoengine/document.py", line 177, in save
    _refs=_refs)
  File "/home/vagrant/.virtualenvs/engineclub/lib/python2.6/site-packages/mongoengine/document.py", line 183, in save
    raise OperationError(message % unicode(err))
OperationError: Tried to save duplicate unique keys (E11000 duplicate key error index: test_aliss.account.$_id_  dup key: { : ObjectId('4f17f0855585d32457000001') })

它似乎在抱怨帐户上有一个重复的密钥。$id当插入一个只引用帐户集合的成员实例时。在

让我知道如果还有其他信息我可以包括,我会添加JSON文件,但它非常像打印的dicts(只有3个帐户后面有一个成员资格)。有一件事我注意到了,当我从save中删除force_insert时,它似乎根本没有保存任何东西(因此看起来没问题)。在


Tags: infrompyimportjsondatamodelsave