Limit length of ListField in mongoengine

1.9k Views Asked by At

Could I limit the length of a ListField data in mongoengie without if condition?

I need something like this:

list = db.ListField(IntField(), max_length = 24)

in my document.

Or I have to check the length of my list when it's going to be update and don't update it if the length of my list greater than 24!

1

There are 1 best solutions below

4
alecxe On BEST ANSWER

There is nothing like this built into the ListField, but you can make your custom ListField providing a max_length attribute:

class MyListField(ListField):
    def __init__(self, max_length=None,  **kwargs):
        self.max_length = max_length
        super(MyListField, self).__init__(**kwargs)

    def validate(self, value):
        super(MyListField, self).validate(value)

        if self.max_length is not None and len(value) > self.max_length:
            self.error('Too many items in the list')