StringField定义为唯一,但重复项以静默方式保存

时间:2012-03-27 11:18:38

标签: django mongodb unique mongoengine

我定义了一个简单的文档,如下所示:

class Company(Document):
    screen_name = StringField(max_length=100, required=True, unique=True)
    official_name = StringField(required=False)

    meta = {
        'indexes': [{'fields': 'screen_name', 'unique': True}]
    }

但是在我写一个测试时

@use_tdb
def test_company3():
    """ test company2 """
    company = Company(screen_name='asdasd')
    company.save()
    company = Company(screen_name='asdasd')
    with nt.assert_raises(OperationError):
        company.save()
        pprint([(x.id, x.screen_name,) for x in Company.objects.all()])

它实际上保存了它们。我在输出中看到了:

[(ObjectId('4f719f915c121a21ad000003'), u'asdasd'),
 (ObjectId('4f719f915c121a21ad000004'), u'asdasd')]

任何想法,我做错了什么?

由于

1 个答案:

答案 0 :(得分:2)

可能需要drop_collection。

def test_company3():
    """ test company2 """
    Company.drop_collection()
    company = Company(screen_name='asdasd')
    company.save()
    company = Company(screen_name='asdasd')
    with nt.assert_raises(OperationError):
        company.save()
    pprint([(x.id, x.screen_name,) for x in Company.objects.all()])

参见此测试。 Mongoengine是所有测试通过。 https://github.com/hmarr/mongoengine/blob/master/tests/document.py#L875

Mongoengine团队最近重新发布了0.6.3。