其他unique_with

问题描述 投票:6回答:3

我正在使用MongoDB的mongoengine。我必须创建一个文档,其中元组(merchant_id,order_id,event_type)必须是唯一键。

直到现在,我始终把独特性局限于两个领域。以下工作 -

merchant_id = StringField(required = True)
order_id = StringField(required = True, unique_with = 'merchant_id')

现在,我正在尝试为三个领域做到这一点 -

merchant_id = StringField(required = True)
order_id =  StringField(required = True)
event_type = StringField(
    required = True,
    unique_with = ['merchant_id', 'order_id'])

但这不起作用。我没有在模块中收到错误。但如果我输入数据 -

merchant_id = 'Merchant1'
order_id = 'Order1'
event_type = 'Event1'

然后尝试使用相同的merchant_idorder_id添加另一个数据但是使用不同的event_id,然后它会给出一个关于成为重复键的错误。

我也尝试过:

merchant_id = StringField(required = True)
order_id =  StringField(required = True)
event_type = StringField(
    required = True,
    unique_with = ('merchant_id', 'order_id'))
python mongodb mongoengine
3个回答
2
投票

如果要修改现有索引的参数,则必须先删除索引,然后重新创建它。当然,您无法在包含重复项的集合上创建唯一索引。您必须先删除重复项,或使用“dropDups”索引创建选项。


7
投票

您可以在类的元字典中指定indexes

meta = {
    'indexes': [
        {'fields': ('merchant_id', 'order_id'), 'unique': True}
    ]
}

0
投票

确保创建索引,否则也不会生成'unique': True索引,也不会生成unique_with字段。

meta = {
    'auto_create_index': True
}
© www.soinside.com 2019 - 2024. All rights reserved.