Python django.contrib.postgres.fields.ArrayField() Examples

The following are 30 code examples of django.contrib.postgres.fields.ArrayField(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.postgres.fields , or try the search function .
Example #1
Source File: context.py    From django-stubs with MIT License 6 votes vote down vote up
def get_field_set_type(self, api: TypeChecker, field: Union[Field, ForeignObjectRel], *, method: str) -> MypyType:
        """ Get a type of __set__ for this specific Django field. """
        target_field = field
        if isinstance(field, ForeignKey):
            target_field = field.target_field

        field_info = helpers.lookup_class_typeinfo(api, target_field.__class__)
        if field_info is None:
            return AnyType(TypeOfAny.from_error)

        field_set_type = helpers.get_private_descriptor_type(field_info, '_pyi_private_set_type',
                                                             is_nullable=self.get_field_nullability(field, method))
        if isinstance(target_field, ArrayField):
            argument_field_type = self.get_field_set_type(api, target_field.base_field, method=method)
            field_set_type = helpers.convert_any_to_type(field_set_type, argument_field_type)
        return field_set_type 
Example #2
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_icontains(self):
        # Using the __icontains lookup with ArrayField is inefficient.
        instance = CharArrayModel.objects.create(field=['FoO'])
        self.assertSequenceEqual(
            CharArrayModel.objects.filter(field__icontains='foo'),
            [instance]
        ) 
Example #3
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_invalid_default(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.IntegerField(), default=[])

        model = MyModel()
        self.assertEqual(model.check(), [
            checks.Warning(
                msg=(
                    "ArrayField default should be a callable instead of an "
                    "instance so that it's not shared between all field "
                    "instances."
                ),
                hint='Use a callable instead, e.g., use `list` instead of `[]`.',
                obj=MyModel._meta.get_field('field'),
                id='postgres.E003',
            )
        ]) 
Example #4
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_invalid_default(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.IntegerField(), default=[])

        model = MyModel()
        self.assertEqual(model.check(), [
            checks.Warning(
                msg=(
                    "ArrayField default should be a callable instead of an "
                    "instance so that it's not shared between all field "
                    "instances."
                ),
                hint='Use a callable instead, e.g., use `list` instead of `[]`.',
                obj=MyModel._meta.get_field('field'),
                id='postgres.E003',
            )
        ]) 
Example #5
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_icontains(self):
        # Using the __icontains lookup with ArrayField is inefficient.
        instance = CharArrayModel.objects.create(field=['FoO'])
        self.assertSequenceEqual(
            CharArrayModel.objects.filter(field__icontains='foo'),
            [instance]
        ) 
Example #6
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_field_choices(self):
        model_field = ArrayField(models.IntegerField(choices=((1, 'A'), (2, 'B'))))
        form_field = model_field.formfield()
        self.assertEqual(form_field.clean('1,2'), [1, 2]) 
Example #7
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_checks(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.CharField())

        model = MyModel()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        # The inner CharField is missing a max_length.
        self.assertEqual(errors[0].id, 'postgres.E001')
        self.assertIn('max_length', errors[0].msg) 
Example #8
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_base_fields(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.ManyToManyField('postgres_tests.IntegerArrayModel'))

        model = MyModel()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].id, 'postgres.E002') 
Example #9
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_default(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.IntegerField(), default=list)

        model = MyModel()
        self.assertEqual(model.check(), []) 
Example #10
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_default_none(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.IntegerField(), default=None)

        model = MyModel()
        self.assertEqual(model.check(), []) 
Example #11
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deconstruct(self):
        field = ArrayField(models.IntegerField())
        name, path, args, kwargs = field.deconstruct()
        new = ArrayField(*args, **kwargs)
        self.assertEqual(type(new.base_field), type(field.base_field))
        self.assertIsNot(new.base_field, field.base_field) 
Example #12
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deconstruct_with_size(self):
        field = ArrayField(models.IntegerField(), size=3)
        name, path, args, kwargs = field.deconstruct()
        new = ArrayField(*args, **kwargs)
        self.assertEqual(new.size, field.size) 
Example #13
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deconstruct_args(self):
        field = ArrayField(models.CharField(max_length=20))
        name, path, args, kwargs = field.deconstruct()
        new = ArrayField(*args, **kwargs)
        self.assertEqual(new.base_field.max_length, field.base_field.max_length) 
Example #14
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_subclass_deconstruct(self):
        field = ArrayField(models.IntegerField())
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, 'django.contrib.postgres.fields.ArrayField')

        field = ArrayFieldSubclass()
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(path, 'postgres_tests.models.ArrayFieldSubclass') 
Example #15
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_adding_arrayfield_with_index(self):
        """
        ArrayField shouldn't have varchar_patterns_ops or text_patterns_ops indexes.
        """
        table_name = 'postgres_tests_chartextarrayindexmodel'
        call_command('migrate', 'postgres_tests', verbosity=0)
        with connection.cursor() as cursor:
            like_constraint_columns_list = [
                v['columns']
                for k, v in list(connection.introspection.get_constraints(cursor, table_name).items())
                if k.endswith('_like')
            ]
        # Only the CharField should have a LIKE index.
        self.assertEqual(like_constraint_columns_list, [['char2']])
        # All fields should have regular indexes.
        with connection.cursor() as cursor:
            indexes = [
                c['columns'][0]
                for c in connection.introspection.get_constraints(cursor, table_name).values()
                if c['index'] and len(c['columns']) == 1
            ]
        self.assertIn('char', indexes)
        self.assertIn('char2', indexes)
        self.assertIn('text', indexes)
        call_command('migrate', 'postgres_tests', 'zero', verbosity=0)
        with connection.cursor() as cursor:
            self.assertNotIn(table_name, connection.introspection.table_names(cursor)) 
Example #16
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_blank_true(self):
        field = ArrayField(models.IntegerField(blank=True, null=True))
        # This should not raise a validation error
        field.clean([1, None], None) 
Example #17
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_with_size(self):
        field = ArrayField(models.IntegerField(), size=3)
        field.clean([1, 2, 3], None)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean([1, 2, 3, 4], None)
        self.assertEqual(cm.exception.messages[0], 'List contains 4 items, it should contain no more than 3.') 
Example #18
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_nested_array_mismatch(self):
        field = ArrayField(ArrayField(models.IntegerField()))
        field.clean([[1, 2], [3, 4]], None)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean([[1, 2], [3, 4, 5]], None)
        self.assertEqual(cm.exception.code, 'nested_array_mismatch')
        self.assertEqual(cm.exception.messages[0], 'Nested arrays must have the same length.') 
Example #19
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_with_base_field_error_params(self):
        field = ArrayField(models.CharField(max_length=2))
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean(['abc'], None)
        self.assertEqual(len(cm.exception.error_list), 1)
        exception = cm.exception.error_list[0]
        self.assertEqual(
            exception.message,
            'Item 1 in the array did not validate: Ensure this value has at most 2 characters (it has 3).'
        )
        self.assertEqual(exception.code, 'item_invalid')
        self.assertEqual(exception.params, {'nth': 1, 'value': 'abc', 'limit_value': 2, 'show_value': 3}) 
Example #20
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_with_validators(self):
        field = ArrayField(models.IntegerField(validators=[validators.MinValueValidator(1)]))
        field.clean([1, 2], None)
        with self.assertRaises(exceptions.ValidationError) as cm:
            field.clean([0], None)
        self.assertEqual(len(cm.exception.error_list), 1)
        exception = cm.exception.error_list[0]
        self.assertEqual(
            exception.message,
            'Item 1 in the array did not validate: Ensure this value is greater than or equal to 1.'
        )
        self.assertEqual(exception.code, 'item_invalid')
        self.assertEqual(exception.params, {'nth': 1, 'value': 0, 'limit_value': 1, 'show_value': 0}) 
Example #21
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_field_formfield_size(self):
        model_field = ArrayField(models.CharField(max_length=27), size=4)
        form_field = model_field.formfield()
        self.assertIsInstance(form_field, SimpleArrayField)
        self.assertEqual(form_field.max_length, 4) 
Example #22
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_model_field_choices(self):
        model_field = ArrayField(models.IntegerField(choices=((1, 'A'), (2, 'B'))))
        form_field = model_field.formfield()
        self.assertEqual(form_field.clean('1,2'), [1, 2]) 
Example #23
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_deconstruct_with_size(self):
        field = ArrayField(models.IntegerField(), size=3)
        name, path, args, kwargs = field.deconstruct()
        new = ArrayField(*args, **kwargs)
        self.assertEqual(new.size, field.size) 
Example #24
Source File: general.py    From Hands-On-Application-Development-with-PyCharm with MIT License 5 votes vote down vote up
def output_field(self):
        return ArrayField(self.source_expressions[0].output_field) 
Example #25
Source File: stringifier.py    From django_audit_trail with Apache License 2.0 5 votes vote down vote up
def stringify(cls, field, value=None):
        value = value
        field_class = field.__class__

        if field_class in cls.custom_stringify_methods:
            stringifier = cls.custom_stringify_methods[field_class]

            if isinstance(stringifier, six.string_types):
                stringifier = getattr(cls, stringifier)

            return stringifier(value, field)

        if value is None:
            return None

        if isinstance(field, IntegerField):
            value = int(value)

        if isinstance(field, ArrayField):
            return force_text(', '.join(value))

        if getattr(field, 'choices', None):
            try:
                choices_dict = dict(field.choices)
                value = choices_dict[value]
                return force_text(value)
            except (KeyError, TypeError):
                return force_text(value)

        return force_text(value) 
Example #26
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_unsupported_lookup(self):
        msg = "Unsupported lookup '0_bar' for ArrayField or join on the field not permitted."
        with self.assertRaisesMessage(FieldError, msg):
            list(NullableIntegerArrayModel.objects.filter(field__0_bar=[2]))

        msg = "Unsupported lookup '0bar' for ArrayField or join on the field not permitted."
        with self.assertRaisesMessage(FieldError, msg):
            list(NullableIntegerArrayModel.objects.filter(field__0bar=[2])) 
Example #27
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_field_checks(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.CharField())

        model = MyModel()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        # The inner CharField is missing a max_length.
        self.assertEqual(errors[0].id, 'postgres.E001')
        self.assertIn('max_length', errors[0].msg) 
Example #28
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_invalid_base_fields(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.ManyToManyField('postgres_tests.IntegerArrayModel'))

        model = MyModel()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        self.assertEqual(errors[0].id, 'postgres.E002') 
Example #29
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_valid_default_none(self):
        class MyModel(PostgreSQLModel):
            field = ArrayField(models.IntegerField(), default=None)

        model = MyModel()
        self.assertEqual(model.check(), []) 
Example #30
Source File: test_array.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_nested_field_checks(self):
        """
        Nested ArrayFields are permitted.
        """
        class MyModel(PostgreSQLModel):
            field = ArrayField(ArrayField(models.CharField()))

        model = MyModel()
        errors = model.check()
        self.assertEqual(len(errors), 1)
        # The inner CharField is missing a max_length.
        self.assertEqual(errors[0].id, 'postgres.E001')
        self.assertIn('max_length', errors[0].msg)