2

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!

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
MDK
  • 680
  • 1
  • 9
  • 20

1 Answers1

5

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')
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Just off the top of my head and not looking right now but cannot [SortedListField](http://docs.mongoengine.org/en/latest/apireference.html#mongoengine.fields.SortedListField) be applied with arguments that effictively do [$slice](http://docs.mongodb.org/manual/reference/operator/update/slice/) as per normal MongoDB array operations? I seem to vaguely remember a test case doing this. But if you can confirm that is not true then great. – Neil Lunn Mar 11 '15 at 08:10
  • wow I don't think about custom Listfield it seems great but I can't understand some syntax like `**kwargs` and `super` and `validate` functions could you tell me about them ? – MDK Mar 11 '15 at 09:50
  • 1
    @MDK sure, `super(MyListField, self).__init__(**kwargs)` would call the `ListField`'s `__init__()` method (see http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods), speaking about `**kwargs` - see http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python. `Field.validate()` method is a base validation method for mongoengine fields, see for example how `StringField` is implemented. Hope that helps. – alecxe Mar 11 '15 at 13:49
  • @NeilLunn from looking into [sources](https://github.com/MongoEngine/mongoengine/blob/dbe8357dd58fa9e2631d681f9e4528848ab74a48/mongoengine/fields.py#L757) I don't think that slicing is handled in a special way, but I might be wrong, my mongodb and mongoengine skills are very rusty at the moment :) – alecxe Mar 11 '15 at 14:00