mongoengine的DictField()

py2.7
mongoengine 0.10.5

pop() 某些key时出现异常(同时更新3个key或以上)。不知原因。

    from mongoengine import connect, Document
    from mongoengine import StringField, DictField

    connect('default-db')


    class User(Document):
        # name = StringField(max_length=50, default='')  # 用户名
        properties = DictField()

    # User(properties={'show_1': True, 'show_2': True, 'show_3': True, 'show_4': True}).save()
    u = User.objects.all().first()
    if not u.properties:
        u.properties = {}
    print(u.properties)

    show_1 = 1
    show_2 = 1
    show_3 = 0
    show_4 = 1


    def __fun(attr, name, d):
        if attr:
            d[name] = True
        elif not attr and name in d:
            d.pop(name)  # error
            # d[name] = False  # ok


    __fun(show_1, 'show_1', u.properties)
    __fun(show_2, 'show_2', u.properties)
    __fun(show_3, 'show_3', u.properties)
    __fun(show_4, 'show_4', u.properties)
   
    # u.properties['show_1'] = True
    # u.properties['show_2'] = True
    # u.properties['show_4'] = True
    # u.properties.pop('show_3')  # error

    print(u.properties)
    
    # mongoengine.errors.OperationError: Could not save document (Cannot update 'properties' and 'properties.show_2' at the same time)
    u.save()

py3.5
mongoengine 0.11.0 正常

你可能感兴趣的:(mongoengine的DictField())