Python django.db.models.Index() Examples

The following are 30 code examples for showing how to use django.db.models.Index(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: django-more   Author: ashleywaite   File: indexes.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_name_with_model(self, model):
        table_name = model._meta.db_table
        column_names = [model._meta.get_field(field_name).column for field_name, order in self.fields_orders]
        column_names_with_order = [
            (('-%s' if order else '%s') % column_name)
            for column_name, (field_name, order) in zip(column_names, self.fields_orders)
        ]
        hash_data = [table_name] + column_names_with_order + [self.suffix] + [self.get_where_sql(self.get_query(model))]
        self.name = '%s_%s_%s' % (
            table_name[:11],
            column_names[0][:7],
            '%s_%s' % (self._hash_generator(*hash_data), self.suffix),
        )
        assert len(self.name) <= self.max_name_length, (
            'Index too long for multiple database support. Is self.suffix '
            'longer than 3 characters?'
        )
        self.check_name() 
Example 2
Project: django-sqlserver   Author: denisenkom   File: test_state.py    License: MIT License 6 votes vote down vote up
def test_abstract_model_children_inherit_indexes(self):
        class Abstract(models.Model):
            name = models.CharField(max_length=50)

            class Meta:
                app_label = 'migrations'
                abstract = True
                indexes = [models.indexes.Index(fields=['name'])]

        class Child1(Abstract):
            pass

        class Child2(Abstract):
            pass

        child1_state = ModelState.from_model(Child1)
        child2_state = ModelState.from_model(Child2)
        index_names = [index.name for index in child1_state.options['indexes']]
        self.assertEqual(index_names, ['migrations__name_b0afd7_idx'])
        index_names = [index.name for index in child2_state.options['indexes']]
        self.assertEqual(index_names, ['migrations__name_016466_idx'])

        # Modifying the state doesn't modify the index on the model.
        child1_state.options['indexes'][0].name = 'bar'
        self.assertEqual(Child1._meta.indexes[0].name, 'migrations__name_b0afd7_idx') 
Example 3
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 6 votes vote down vote up
def test_alter_field_with_index(self):
        """
        Test AlterField operation with an index to ensure indexes created via
        Meta.indexes don't get dropped with sqlite3 remake.
        """
        project_state = self.set_up_test_model("test_alflin", index=True)
        operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflin", new_state)
        # Test the database alteration
        self.assertColumnNotNull("test_alflin_pony", "pink")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflin", editor, project_state, new_state)
        # Index hasn't been dropped
        self.assertIndexExists("test_alflin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflin", editor, new_state, project_state)
        # Ensure the index is still there
        self.assertIndexExists("test_alflin_pony", ["pink"]) 
Example 4
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 6 votes vote down vote up
def test_indexes_ignore_swapped(self):
        """
        Add/RemoveIndex operations ignore swapped models.
        """
        operation = migrations.AddIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
        project_state, new_state = self.make_test_state('test_adinigsw', operation)
        with connection.schema_editor() as editor:
            # No database queries should be run for swapped models
            operation.database_forwards('test_adinigsw', editor, project_state, new_state)
            operation.database_backwards('test_adinigsw', editor, new_state, project_state)

        operation = migrations.RemoveIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
        project_state, new_state = self.make_test_state("test_rminigsw", operation)
        with connection.schema_editor() as editor:
            operation.database_forwards('test_rminigsw', editor, project_state, new_state)
            operation.database_backwards('test_rminigsw', editor, new_state, project_state) 
Example 5
Project: django-sqlserver   Author: denisenkom   File: test_autodetector.py    License: MIT License 6 votes vote down vote up
def test_create_model_with_indexes(self):
        """Test creation of new model with indexes already defined."""
        author = ModelState('otherapp', 'Author', [
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
        ], {'indexes': [models.Index(fields=['name'], name='create_model_with_indexes_idx')]})
        changes = self.get_changes([], [author])
        added_index = models.Index(fields=['name'], name='create_model_with_indexes_idx')
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 2)
        # Right actions order?
        self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddIndex'])
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author')
        self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', index=added_index) 
Example 6
Project: djongo   Author: nesdis   File: test_models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_pointing_to_non_local_field(self):
        class Foo(models.Model):
            field1 = models.IntegerField()

        class Bar(Foo):
            field2 = models.IntegerField()

            class Meta:
                indexes = [models.Index(fields=['field2', 'field1'], name='name')]

        self.assertEqual(Bar.check(), [
            Error(
                "'indexes' refers to field 'field1' which is not local to "
                "model 'Bar'.",
                hint='This issue may be caused by multi-table inheritance.',
                obj=Bar,
                id='models.E016',
            ),
        ]) 
Example 7
Project: djongo   Author: nesdis   File: test_state.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_abstract_model_children_inherit_indexes(self):
        class Abstract(models.Model):
            name = models.CharField(max_length=50)

            class Meta:
                app_label = 'migrations'
                abstract = True
                indexes = [models.indexes.Index(fields=['name'])]

        class Child1(Abstract):
            pass

        class Child2(Abstract):
            pass

        child1_state = ModelState.from_model(Child1)
        child2_state = ModelState.from_model(Child2)
        index_names = [index.name for index in child1_state.options['indexes']]
        self.assertEqual(index_names, ['migrations__name_b0afd7_idx'])
        index_names = [index.name for index in child2_state.options['indexes']]
        self.assertEqual(index_names, ['migrations__name_016466_idx'])

        # Modifying the state doesn't modify the index on the model.
        child1_state.options['indexes'][0].name = 'bar'
        self.assertEqual(Child1._meta.indexes[0].name, 'migrations__name_b0afd7_idx') 
Example 8
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_with_index(self):
        """
        Test AlterField operation with an index to ensure indexes created via
        Meta.indexes don't get dropped with sqlite3 remake.
        """
        project_state = self.set_up_test_model("test_alflin", index=True)
        operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflin", new_state)
        # Test the database alteration
        self.assertColumnNotNull("test_alflin_pony", "pink")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflin", editor, project_state, new_state)
        # Index hasn't been dropped
        self.assertIndexExists("test_alflin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflin", editor, new_state, project_state)
        # Ensure the index is still there
        self.assertIndexExists("test_alflin_pony", ["pink"]) 
Example 9
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_indexes_ignore_swapped(self):
        """
        Add/RemoveIndex operations ignore swapped models.
        """
        operation = migrations.AddIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
        project_state, new_state = self.make_test_state('test_adinigsw', operation)
        with connection.schema_editor() as editor:
            # No database queries should be run for swapped models
            operation.database_forwards('test_adinigsw', editor, project_state, new_state)
            operation.database_backwards('test_adinigsw', editor, new_state, project_state)

        operation = migrations.RemoveIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
        project_state, new_state = self.make_test_state("test_rminigsw", operation)
        with connection.schema_editor() as editor:
            operation.database_forwards('test_rminigsw', editor, project_state, new_state)
            operation.database_backwards('test_rminigsw', editor, new_state, project_state) 
Example 10
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_name_auto_generation(self):
        index = models.Index(fields=['author'])
        index.set_name_with_model(Book)
        self.assertEqual(index.name, 'model_index_author_0f5565_idx')

        # '-' for DESC columns should be accounted for in the index name.
        index = models.Index(fields=['-author'])
        index.set_name_with_model(Book)
        self.assertEqual(index.name, 'model_index_author_708765_idx')

        # fields may be truncated in the name. db_column is used for naming.
        long_field_index = models.Index(fields=['pages'])
        long_field_index.set_name_with_model(Book)
        self.assertEqual(long_field_index.name, 'model_index_page_co_69235a_idx')

        # suffix can't be longer than 3 characters.
        long_field_index.suffix = 'suff'
        msg = 'Index too long for multiple database support. Is self.suffix longer than 3 characters?'
        with self.assertRaisesMessage(AssertionError, msg):
            long_field_index.set_name_with_model(Book) 
Example 11
Project: djongo   Author: nesdis   File: test_state.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_abstract_model_children_inherit_indexes(self):
        class Abstract(models.Model):
            name = models.CharField(max_length=50)

            class Meta:
                app_label = 'migrations'
                abstract = True
                indexes = [models.indexes.Index(fields=['name'])]

        class Child1(Abstract):
            pass

        class Child2(Abstract):
            pass

        child1_state = ModelState.from_model(Child1)
        child2_state = ModelState.from_model(Child2)
        index_names = [index.name for index in child1_state.options['indexes']]
        self.assertEqual(index_names, ['migrations__name_b0afd7_idx'])
        index_names = [index.name for index in child2_state.options['indexes']]
        self.assertEqual(index_names, ['migrations__name_016466_idx'])

        # Modifying the state doesn't modify the index on the model.
        child1_state.options['indexes'][0].name = 'bar'
        self.assertEqual(Child1._meta.indexes[0].name, 'migrations__name_b0afd7_idx') 
Example 12
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_alter_field_with_index(self):
        """
        Test AlterField operation with an index to ensure indexes created via
        Meta.indexes don't get dropped with sqlite3 remake.
        """
        project_state = self.set_up_test_model("test_alflin", index=True)
        operation = migrations.AlterField("Pony", "pink", models.IntegerField(null=True))
        new_state = project_state.clone()
        operation.state_forwards("test_alflin", new_state)
        # Test the database alteration
        self.assertColumnNotNull("test_alflin_pony", "pink")
        with connection.schema_editor() as editor:
            operation.database_forwards("test_alflin", editor, project_state, new_state)
        # Index hasn't been dropped
        self.assertIndexExists("test_alflin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_alflin", editor, new_state, project_state)
        # Ensure the index is still there
        self.assertIndexExists("test_alflin_pony", ["pink"]) 
Example 13
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_indexes_ignore_swapped(self):
        """
        Add/RemoveIndex operations ignore swapped models.
        """
        operation = migrations.AddIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
        project_state, new_state = self.make_test_state('test_adinigsw', operation)
        with connection.schema_editor() as editor:
            # No database queries should be run for swapped models
            operation.database_forwards('test_adinigsw', editor, project_state, new_state)
            operation.database_backwards('test_adinigsw', editor, new_state, project_state)

        operation = migrations.RemoveIndex('Pony', models.Index(fields=['pink'], name='my_name_idx'))
        project_state, new_state = self.make_test_state("test_rminigsw", operation)
        with connection.schema_editor() as editor:
            operation.database_forwards('test_rminigsw', editor, project_state, new_state)
            operation.database_backwards('test_rminigsw', editor, new_state, project_state) 
Example 14
Project: djongo   Author: nesdis   File: test_autodetector.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_create_model_with_indexes(self):
        """Test creation of new model with indexes already defined."""
        author = ModelState('otherapp', 'Author', [
            ('id', models.AutoField(primary_key=True)),
            ('name', models.CharField(max_length=200)),
        ], {'indexes': [models.Index(fields=['name'], name='create_model_with_indexes_idx')]})
        changes = self.get_changes([], [author])
        added_index = models.Index(fields=['name'], name='create_model_with_indexes_idx')
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 2)
        # Right actions order?
        self.assertOperationTypes(changes, 'otherapp', 0, ['CreateModel', 'AddIndex'])
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, name='Author')
        self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='author', index=added_index) 
Example 15
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_index_name(self):
        """
        Index names on the built-in database backends::
            * Are truncated as needed.
            * Include all the column names.
            * Include a deterministic hash.
        """
        long_name = 'l%sng' % ('o' * 100)
        editor = connection.schema_editor()
        index_name = editor._create_index_name(
            table_name=Article._meta.db_table,
            column_names=('c1', 'c2', long_name),
            suffix='ix',
        )
        expected = {
            'mysql': 'indexes_article_c1_c2_looooooooooooooooooo_255179b2ix',
            'oracle': 'indexes_a_c1_c2_loo_255179b2ix',
            'postgresql': 'indexes_article_c1_c2_loooooooooooooooooo_255179b2ix',
            'sqlite': 'indexes_article_c1_c2_l%sng_255179b2ix' % ('o' * 100),
        }
        if connection.vendor not in expected:
            self.skipTest('This test is only supported on the built-in database backends.')
        self.assertEqual(index_name, expected[connection.vendor]) 
Example 16
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_partial_index(self):
        with connection.schema_editor() as editor:
            index = Index(
                name='recent_article_idx',
                fields=['pub_date'],
                condition=Q(
                    pub_date__gt=datetime.datetime(
                        year=2015, month=1, day=1,
                        # PostgreSQL would otherwise complain about the lookup
                        # being converted to a mutable function (by removing
                        # the timezone in the cast) which is forbidden.
                        tzinfo=timezone.get_current_timezone(),
                    ),
                )
            )
            self.assertIn(
                'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name("pub_date")),
                str(index.create_sql(Article, schema_editor=editor))
            )
            editor.add_index(index=index, model=Article)
            self.assertIn(index.name, connection.introspection.get_constraints(
                cursor=connection.cursor(), table_name=Article._meta.db_table,
            ))
            editor.remove_index(index=index, model=Article) 
Example 17
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_integer_restriction_partial(self):
        with connection.schema_editor() as editor:
            index = Index(
                name='recent_article_idx',
                fields=['id'],
                condition=Q(pk__gt=1),
            )
            self.assertIn(
                'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name('id')),
                str(index.create_sql(Article, schema_editor=editor))
            )
            editor.add_index(index=index, model=Article)
            self.assertIn(index.name, connection.introspection.get_constraints(
                cursor=connection.cursor(), table_name=Article._meta.db_table,
            ))
            editor.remove_index(index=index, model=Article) 
Example 18
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_boolean_restriction_partial(self):
        with connection.schema_editor() as editor:
            index = Index(
                name='published_index',
                fields=['published'],
                condition=Q(published=True),
            )
            self.assertIn(
                'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name('published')),
                str(index.create_sql(Article, schema_editor=editor))
            )
            editor.add_index(index=index, model=Article)
            self.assertIn(index.name, connection.introspection.get_constraints(
                cursor=connection.cursor(), table_name=Article._meta.db_table,
            ))
            editor.remove_index(index=index, model=Article) 
Example 19
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_name_auto_generation(self):
        index = models.Index(fields=['author'])
        index.set_name_with_model(Book)
        self.assertEqual(index.name, 'model_index_author_0f5565_idx')

        # '-' for DESC columns should be accounted for in the index name.
        index = models.Index(fields=['-author'])
        index.set_name_with_model(Book)
        self.assertEqual(index.name, 'model_index_author_708765_idx')

        # fields may be truncated in the name. db_column is used for naming.
        long_field_index = models.Index(fields=['pages'])
        long_field_index.set_name_with_model(Book)
        self.assertEqual(long_field_index.name, 'model_index_page_co_69235a_idx')

        # suffix can't be longer than 3 characters.
        long_field_index.suffix = 'suff'
        msg = 'Index too long for multiple database support. Is self.suffix longer than 3 characters?'
        with self.assertRaisesMessage(AssertionError, msg):
            long_field_index.set_name_with_model(Book) 
Example 20
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_deconstruct_with_condition(self):
        index = models.Index(
            name='big_book_index',
            fields=['title'],
            condition=Q(pages__gt=400),
        )
        index.set_name_with_model(Book)
        path, args, kwargs = index.deconstruct()
        self.assertEqual(path, 'django.db.models.Index')
        self.assertEqual(args, ())
        self.assertEqual(
            kwargs,
            {
                'fields': ['title'],
                'name': 'model_index_title_196f42_idx',
                'condition': Q(pages__gt=400),
            }
        ) 
Example 21
Project: django-sqlserver   Author: denisenkom   File: test_state.py    License: MIT License 5 votes vote down vote up
def test_sanity_index_name(self):
        field = models.IntegerField()
        options = {'indexes': [models.Index(fields=['field'])]}
        msg = "Indexes passed to ModelState require a name attribute. <Index: fields='field'> doesn't have one."
        with self.assertRaisesMessage(ValueError, msg):
            ModelState('app', 'Model', [('field', field)], options=options) 
Example 22
Project: django-sqlserver   Author: denisenkom   File: test_state.py    License: MIT License 5 votes vote down vote up
def test_explicit_index_name(self):
        class TestModel(models.Model):
            name = models.CharField(max_length=50)

            class Meta:
                app_label = 'migrations'
                indexes = [models.indexes.Index(fields=['name'], name='foo_idx')]

        model_state = ModelState.from_model(TestModel)
        index_names = [index.name for index in model_state.options['indexes']]
        self.assertEqual(index_names, ['foo_idx']) 
Example 23
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 5 votes vote down vote up
def test_add_index(self):
        """
        Test the AddIndex operation.
        """
        project_state = self.set_up_test_model("test_adin")
        msg = (
            "Indexes passed to AddIndex operations require a name argument. "
            "<Index: fields='pink'> doesn't have one."
        )
        with self.assertRaisesMessage(ValueError, msg):
            migrations.AddIndex("Pony", models.Index(fields=["pink"]))
        index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx")
        operation = migrations.AddIndex("Pony", index)
        self.assertEqual(operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony")
        new_state = project_state.clone()
        operation.state_forwards("test_adin", new_state)
        # Test the database alteration
        self.assertEqual(len(new_state.models["test_adin", "pony"].options['indexes']), 1)
        self.assertIndexNotExists("test_adin_pony", ["pink"])
        with connection.schema_editor() as editor:
            operation.database_forwards("test_adin", editor, project_state, new_state)
        self.assertIndexExists("test_adin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_adin", editor, new_state, project_state)
        self.assertIndexNotExists("test_adin_pony", ["pink"])
        # And deconstruction
        definition = operation.deconstruct()
        self.assertEqual(definition[0], "AddIndex")
        self.assertEqual(definition[1], [])
        self.assertEqual(definition[2], {'model_name': "Pony", 'index': index}) 
Example 24
Project: django-sqlserver   Author: denisenkom   File: test_operations.py    License: MIT License 5 votes vote down vote up
def test_add_index_state_forwards(self):
        project_state = self.set_up_test_model('test_adinsf')
        index = models.Index(fields=['pink'], name='test_adinsf_pony_pink_idx')
        old_model = project_state.apps.get_model('test_adinsf', 'Pony')
        new_state = project_state.clone()

        operation = migrations.AddIndex('Pony', index)
        operation.state_forwards('test_adinsf', new_state)
        new_model = new_state.apps.get_model('test_adinsf', 'Pony')
        self.assertIsNot(old_model, new_model) 
Example 25
Project: django-sqlserver   Author: denisenkom   File: test_autodetector.py    License: MIT License 5 votes vote down vote up
def test_add_indexes(self):
        """Test change detection of new indexes."""
        changes = self.get_changes([self.author_empty, self.book], [self.author_empty, self.book_indexes])
        self.assertNumberMigrations(changes, 'otherapp', 1)
        self.assertOperationTypes(changes, 'otherapp', 0, ['AddIndex'])
        added_index = models.Index(fields=['author', 'title'], name='book_title_author_idx')
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', index=added_index) 
Example 26
Project: django-sqlserver   Author: denisenkom   File: test_autodetector.py    License: MIT License 5 votes vote down vote up
def test_order_fields_indexes(self):
        """Test change detection of reordering of fields in indexes."""
        changes = self.get_changes(
            [self.author_empty, self.book_indexes], [self.author_empty, self.book_unordered_indexes]
        )
        self.assertNumberMigrations(changes, 'otherapp', 1)
        self.assertOperationTypes(changes, 'otherapp', 0, ['RemoveIndex', 'AddIndex'])
        self.assertOperationAttributes(changes, 'otherapp', 0, 0, model_name='book', name='book_title_author_idx')
        added_index = models.Index(fields=['title', 'author'], name='book_author_title_idx')
        self.assertOperationAttributes(changes, 'otherapp', 0, 1, model_name='book', index=added_index) 
Example 27
Project: djongo   Author: nesdis   File: test_models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_pointing_to_missing_field(self):
        class Model(models.Model):
            class Meta:
                indexes = [models.Index(fields=['missing_field'], name='name')]

        self.assertEqual(Model.check(), [
            Error(
                "'indexes' refers to the nonexistent field 'missing_field'.",
                obj=Model,
                id='models.E012',
            ),
        ]) 
Example 28
Project: djongo   Author: nesdis   File: test_models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_pointing_to_m2m_field(self):
        class Model(models.Model):
            m2m = models.ManyToManyField('self')

            class Meta:
                indexes = [models.Index(fields=['m2m'], name='name')]

        self.assertEqual(Model.check(), [
            Error(
                "'indexes' refers to a ManyToManyField 'm2m', but "
                "ManyToManyFields are not permitted in 'indexes'.",
                obj=Model,
                id='models.E013',
            ),
        ]) 
Example 29
Project: djongo   Author: nesdis   File: test_state.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_sanity_index_name(self):
        field = models.IntegerField()
        options = {'indexes': [models.Index(fields=['field'])]}
        msg = "Indexes passed to ModelState require a name attribute. <Index: fields='field'> doesn't have one."
        with self.assertRaisesMessage(ValueError, msg):
            ModelState('app', 'Model', [('field', field)], options=options) 
Example 30
Project: djongo   Author: nesdis   File: test_operations.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_add_index(self):
        """
        Test the AddIndex operation.
        """
        project_state = self.set_up_test_model("test_adin")
        msg = (
            "Indexes passed to AddIndex operations require a name argument. "
            "<Index: fields='pink'> doesn't have one."
        )
        with self.assertRaisesMessage(ValueError, msg):
            migrations.AddIndex("Pony", models.Index(fields=["pink"]))
        index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx")
        operation = migrations.AddIndex("Pony", index)
        self.assertEqual(operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony")
        new_state = project_state.clone()
        operation.state_forwards("test_adin", new_state)
        # Test the database alteration
        self.assertEqual(len(new_state.models["test_adin", "pony"].options['indexes']), 1)
        self.assertIndexNotExists("test_adin_pony", ["pink"])
        with connection.schema_editor() as editor:
            operation.database_forwards("test_adin", editor, project_state, new_state)
        self.assertIndexExists("test_adin_pony", ["pink"])
        # And test reversal
        with connection.schema_editor() as editor:
            operation.database_backwards("test_adin", editor, new_state, project_state)
        self.assertIndexNotExists("test_adin_pony", ["pink"])
        # And deconstruction
        definition = operation.deconstruct()
        self.assertEqual(definition[0], "AddIndex")
        self.assertEqual(definition[1], [])
        self.assertEqual(definition[2], {'model_name': "Pony", 'index': index})