2 8*_*2 8 2 model mongodb mongoengine python-2.7
我有这个模型:
class SourceModel(Document):
name = StringField(
primary_key=True,
max_length=50,
required=True,
)
# some fields
Run Code Online (Sandbox Code Playgroud)
当我尝试运行此代码时:
for source in SOURCES:
SourceModel(**source).save()
Run Code Online (Sandbox Code Playgroud)
我有这个错误:
mongoengine.errors.NotUniqueError: Tried to save duplicate unique keys (E11000 duplicate key error index: mirad.source_model.$name_1 dup key: { : null })
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会发生此错误,原因unique
是我的模型中没有此字段。我将此代码更改为:
for source in SOURCES:
try:
SourceModel(**source).save()
except NotUniqueError:
old_source = SourceModel.objects(name=source['name']).first()
print old_source # this line print None
Run Code Online (Sandbox Code Playgroud)
为什么
您可能没有在文档模型中定义的唯一索引。但是有时会为“名称”创建唯一索引。
因此,您需要在mongodb中删除该索引,可以在shell中这样做,如下所示:
db = new Mongo().getDB("mirad");
db.source_model.dropIndex("name_1")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1382 次 |
最近记录: |