From 1937e1e8e5c260e97bbfe6caf124fb3634ec3acc Mon Sep 17 00:00:00 2001 From: Chaporgin Anton Date: Wed, 19 Aug 2015 00:13:13 +0300 Subject: [PATCH 1/2] Added max_length, min_length keyword arguments to ListField Sometimes it's useful to reject lists if they are too long. E.g. in performance purposes, if you make a database request afterwords, you would prefer not having a request that pulls out thousands of ORM objects after all the validations had passed. And the minimum length I added just to have it there. Don't see any reason to have it for now. --- rest_framework/fields.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 67b1582c9..55cc5b05f 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1375,15 +1375,25 @@ class ListField(Field): initial = [] default_error_messages = { 'not_a_list': _('Expected a list of items but got type "{input_type}".'), - 'empty': _('This list may not be empty.') + 'empty': _('This list may not be empty.'), + 'min_length': _('Ensure this field has at least {min_length} elements.'), + 'max_length': _('Ensure this field has no more than {max_length} elements.'), } def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.allow_empty = kwargs.pop('allow_empty', True) assert not inspect.isclass(self.child), '`child` has not been instantiated.' + max_length = kwargs.pop('max_length', None) + min_length = kwargs.pop('min_length', None) super(ListField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) + if max_length is not None: + message = self.error_messages['max_length'].format(max_length=max_length) + self.validators.append(MaxLengthValidator(max_length, message=message)) + if min_length is not None: + message = self.error_messages['min_length'].format(min_length=self.min_length) + self.validators.append(MinLengthValidator(min_length, message=message)) def get_value(self, dictionary): # We override the default field access in order to support From 4bdd12047d9b94b138f1fd69c213cbbe5e3777b6 Mon Sep 17 00:00:00 2001 From: Anton Chaporgin Date: Wed, 19 Aug 2015 00:26:55 +0300 Subject: [PATCH 2/2] Update fields.py --- rest_framework/fields.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 55cc5b05f..746fc1a4c 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1392,7 +1392,7 @@ class ListField(Field): message = self.error_messages['max_length'].format(max_length=max_length) self.validators.append(MaxLengthValidator(max_length, message=message)) if min_length is not None: - message = self.error_messages['min_length'].format(min_length=self.min_length) + message = self.error_messages['min_length'].format(min_length=min_length) self.validators.append(MinLengthValidator(min_length, message=message)) def get_value(self, dictionary):