Python django.db.models.CASCADE Examples

The following are 30 code examples of django.db.models.CASCADE(). 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.db.models , or try the search function .
Example #1
Source File: patches.py    From django-more with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def ask_remove_enum_values(self, db_type, values):
        """ How to treat records with deleted enum values. """
        # Ordered ensures
        choices = [
            (models.CASCADE, "Cascade - Delete records with removed values"),
            (models.PROTECT, "Protect - Block migrations if records contain removed values"),
            (models.SET_NULL, "Set NULL - Set value to NULL"),
            (models.SET_DEFAULT, "Set default - Set value to field default"),
            (models.SET, "Set value - Provide a one off default now"),
            (models.DO_NOTHING, "Do nothing - Consistency must be handled elsewhere"),
            (None, "Leave it to field definitions")]
        choice, _ = choices[self._choice_input(
            "Enum {db_type} has had {values} removed, "
            "existing records may need to be updated. "
            "Override update behaviour or do nothing and follow field behaviour.".format(
                db_type=db_type,
                values=values),
            [q for (k, q) in choices]) - 1]
        if choice == models.SET:
            return models.SET(self._ask_default())
        return choice 
Example #2
Source File: test_cluster.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def test_parental_key_checks_clusterable_model(self):
        from django.core import checks
        from django.db import models
        from modelcluster.fields import ParentalKey

        class Instrument(models.Model):
            # Oops, BandMember is not a Clusterable model
            member = ParentalKey(BandMember, on_delete=models.CASCADE)

            class Meta:
                # Prevent Django from thinking this is in the database
                # This shouldn't affect the test
                abstract = True

        # Check for error
        errors = Instrument.check()
        self.assertEqual(1, len(errors))

        # Check the error itself
        error = errors[0]
        self.assertIsInstance(error, checks.Error)
        self.assertEqual(error.id, 'modelcluster.E001')
        self.assertEqual(error.obj, Instrument.member.field)
        self.assertEqual(error.msg, 'ParentalKey must point to a subclass of ClusterableModel.')
        self.assertEqual(error.hint, 'Change tests.BandMember into a ClusterableModel or use a ForeignKey instead.') 
Example #3
Source File: test_relative_fields.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_relationship_model_missing_foreign_key(self):
        class Person(models.Model):
            pass

        class Group(models.Model):
            members = models.ManyToManyField('Person', through="InvalidRelationship")

        class InvalidRelationship(models.Model):
            group = models.ForeignKey(Group, models.CASCADE)
            # No foreign key to Person

        field = Group._meta.get_field('members')
        self.assertEqual(field.check(from_model=Group), [
            Error(
                "The model is used as an intermediate model by "
                "'invalid_models_tests.Group.members', but it does not have "
                "a foreign key to 'Group' or 'Person'.",
                obj=InvalidRelationship,
                id='fields.E336',
            ),
        ]) 
Example #4
Source File: fields.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def __init__(self, to, object_id_field='object_id', content_type_field='content_type',
            for_concrete_model=True, related_query_name=None, limit_choices_to=None, **kwargs):
        kwargs['rel'] = self.rel_class(
            self, to,
            related_query_name=related_query_name,
            limit_choices_to=limit_choices_to,
        )

        kwargs['blank'] = True
        kwargs['on_delete'] = models.CASCADE
        kwargs['editable'] = False
        kwargs['serialize'] = False

        # This construct is somewhat of an abuse of ForeignObject. This field
        # represents a relation from pk to object_id field. But, this relation
        # isn't direct, the join is generated reverse along foreign key. So,
        # the from_field is object_id field, to_field is pk because of the
        # reverse join.
        super(GenericRelation, self).__init__(
            to, from_fields=[object_id_field], to_fields=[], **kwargs)

        self.object_id_field_name = object_id_field
        self.content_type_field_name = content_type_field
        self.for_concrete_model = for_concrete_model 
Example #5
Source File: test_operations.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_remove_field_m2m_with_through(self):
        project_state = self.set_up_test_model("test_rmflmmwt", second_model=True)

        self.assertTableNotExists("test_rmflmmwt_ponystables")
        project_state = self.apply_operations("test_rmflmmwt", project_state, operations=[
            migrations.CreateModel("PonyStables", fields=[
                ("pony", models.ForeignKey('test_rmflmmwt.Pony', models.CASCADE)),
                ("stable", models.ForeignKey('test_rmflmmwt.Stable', models.CASCADE)),
            ]),
            migrations.AddField(
                "Pony", "stables",
                models.ManyToManyField("Stable", related_name="ponies", through='test_rmflmmwt.PonyStables')
            )
        ])
        self.assertTableExists("test_rmflmmwt_ponystables")

        operations = [migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables")]
        self.apply_operations("test_rmflmmwt", project_state, operations=operations) 
Example #6
Source File: test_autodetector.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_create_model_and_unique_together(self):
        author = ModelState("otherapp", "Author", [
            ("id", models.AutoField(primary_key=True)),
            ("name", models.CharField(max_length=200)),
        ])
        book_with_author = ModelState("otherapp", "Book", [
            ("id", models.AutoField(primary_key=True)),
            ("author", models.ForeignKey("otherapp.Author", models.CASCADE)),
            ("title", models.CharField(max_length=200)),
        ], {
            "index_together": {("title", "author")},
            "unique_together": {("title", "author")},
        })
        changes = self.get_changes([self.book_with_no_author], [author, book_with_author])
        # Right number of migrations?
        self.assertEqual(len(changes['otherapp']), 1)
        # Right number of actions?
        migration = changes['otherapp'][0]
        self.assertEqual(len(migration.operations), 4)
        # Right actions order?
        self.assertOperationTypes(
            changes, 'otherapp', 0,
            ['CreateModel', 'AddField', 'AlterUniqueTogether', 'AlterIndexTogether']
        ) 
Example #7
Source File: workflow.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def delete(self, *args, **kwargs):
        # Clear delta history. Deltas can reference WfModules: if we don't
        # clear the deltas, Django may decide to CASCADE to WfModule first and
        # we'll raise a ProtectedError.
        self.clear_deltas()

        # Clear all minio data. We _should_ clear it in pre-delete hooks on
        # StoredObject, UploadedFile, etc.; but [2019-06-03, adamhooper] the
        # database is inconsistent and Django is hard to use so new bugs may
        # crop up anyway.
        #
        # [2019-06-03, adamhooper] hooks never work in ORMs. Better would be
        # to make `delete()` a controller method, not a funky mishmash of
        # Django-ORM absurdities. TODO nix Django ORM.
        #
        # TL;DR we're double-deleting minio data, to be extra-safe. The user
        # said "delete." We'll delete.
        if self.id:  # be extra-safe: use if-statement so we don't remove '/'
            minio.remove_recursive(minio.StoredObjectsBucket, f"{self.id}/")
            minio.remove_recursive(minio.UserFilesBucket, f"wf-{self.id}/")

        super().delete(*args, **kwargs) 
Example #8
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_duplicate_order_field(self):
        class Bar(models.Model):
            class Meta:
                app_label = 'order_with_respect_to'

        class Foo(models.Model):
            bar = models.ForeignKey(Bar, models.CASCADE)
            order = models.OrderWrt()

            class Meta:
                order_with_respect_to = 'bar'
                app_label = 'order_with_respect_to'

        count = 0
        for field in Foo._meta.local_fields:
            if isinstance(field, models.OrderWrt):
                count += 1

        self.assertEqual(count, 1) 
Example #9
Source File: tests.py    From django-sqlserver with MIT License 6 votes vote down vote up
def test_name(self):
        """
        Tests the outputting of the correct name if assigned one.
        """
        # First try using a "normal" field
        field = models.CharField(max_length=65)
        name, path, args, kwargs = field.deconstruct()
        self.assertIsNone(name)
        field.set_attributes_from_name("is_awesome_test")
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(name, "is_awesome_test")
        self.assertIsInstance(name, six.text_type)
        # Now try with a ForeignKey
        field = models.ForeignKey("some_fake.ModelName", models.CASCADE)
        name, path, args, kwargs = field.deconstruct()
        self.assertIsNone(name)
        field.set_attributes_from_name("author")
        name, path, args, kwargs = field.deconstruct()
        self.assertEqual(name, "author") 
Example #10
Source File: test_query.py    From django-seal with MIT License 6 votes vote down vote up
def test_sealed_prefetch_related_non_sealable_model(self):
        class NonSealableClimate(models.Model):
            objects = SealableQuerySet.as_manager()

            class Meta:
                db_table = Climate._meta.db_table

        class NonSealableLocationClimatesThrough(models.Model):
            climate = models.ForeignKey(NonSealableClimate, models.CASCADE)
            location = models.ForeignKey('NonSealableLocation', models.CASCADE)

            class Meta:
                db_table = Location.climates.through._meta.db_table

        class NonSealableLocation(models.Model):
            climates = models.ManyToManyField(NonSealableClimate, through=NonSealableLocationClimatesThrough)

            class Meta:
                db_table = Location._meta.db_table
        queryset = SealableQuerySet(model=NonSealableLocation)
        instance = queryset.prefetch_related('climates').seal().get()
        self.assertTrue(instance._state.sealed)
        with self.assertNumQueries(0):
            self.assertTrue(instance.climates.all()[0]._state.sealed) 
Example #11
Source File: test_expressions.py    From django-localized-fields with MIT License 6 votes vote down vote up
def setUpClass(cls):
        """Creates the test model in the database."""

        super(LocalizedExpressionsTestCase, cls).setUpClass()

        cls.TestModel1 = get_fake_model(
            {"name": models.CharField(null=False, blank=False, max_length=255)}
        )

        cls.TestModel2 = get_fake_model(
            {
                "text": LocalizedField(),
                "other": models.ForeignKey(
                    cls.TestModel1,
                    related_name="features",
                    on_delete=models.CASCADE,
                ),
            }
        ) 
Example #12
Source File: test_cluster.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_parental_key_checks_related_name_is_not_plus(self):
        from django.core import checks
        from django.db import models
        from modelcluster.fields import ParentalKey

        class Instrument(models.Model):
            # Oops, related_name='+' is not allowed
            band = ParentalKey(Band, related_name='+', on_delete=models.CASCADE)

            class Meta:
                # Prevent Django from thinking this is in the database
                # This shouldn't affect the test
                abstract = True

        # Check for error
        errors = Instrument.check()
        self.assertEqual(1, len(errors))

        # Check the error itself
        error = errors[0]
        self.assertIsInstance(error, checks.Error)
        self.assertEqual(error.id, 'modelcluster.E002')
        self.assertEqual(error.obj, Instrument.band.field)
        self.assertEqual(error.msg, "related_name='+' is not allowed on ParentalKey fields")
        self.assertEqual(error.hint, "Either change it to a valid name or remove it") 
Example #13
Source File: test_relative_fields.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_foreign_key_to_missing_model(self):
        # Model names are resolved when a model is being created, so we cannot
        # test relative fields in isolation and we need to attach them to a
        # model.
        class Model(models.Model):
            foreign_key = models.ForeignKey('Rel1', models.CASCADE)

        field = Model._meta.get_field('foreign_key')
        self.assertEqual(field.check(), [
            Error(
                "Field defines a relation with model 'Rel1', "
                "which is either not installed, or is abstract.",
                obj=field,
                id='fields.E300',
            ),
        ]) 
Example #14
Source File: fields.py    From gro-api with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, from_fields, to_fields, swappable=True, **kwargs):
        self.from_fields = from_fields
        self.to_fields = to_fields = to_fields
        self.swappable = swappable

        if 'rel' not in kwargs:
            kwargs['rel'] = LayoutForeignObjectRel(
                self, related_name=kwargs.pop('related_name', None),
                related_query_name=kwargs.pop('related_query_name', None),
                limit_choices_to=kwargs.pop('limit_choices_to', None),
                parent_link=kwargs.pop('parent_link', False),
                on_delete=kwargs.pop('on_delete', CASCADE),
            )
        kwargs['verbose_name'] = kwargs.get('verbose_name', None)

        # We want to skip ForeignObject in the MRO, so we can't use super here
        LayoutRelatedField.__init__(self, **kwargs) 
Example #15
Source File: test_cluster.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_parental_key_checks_target_is_resolved_as_class(self):
        from django.core import checks
        from django.db import models
        from modelcluster.fields import ParentalKey

        class Instrument(models.Model):
            banana = ParentalKey('Banana', on_delete=models.CASCADE)

            class Meta:
                # Prevent Django from thinking this is in the database
                # This shouldn't affect the test
                abstract = True

        # Check for error
        errors = Instrument.check()
        self.assertEqual(1, len(errors))

        # Check the error itself
        error = errors[0]
        self.assertIsInstance(error, checks.Error)
        self.assertEqual(error.id, 'fields.E300')
        self.assertEqual(error.obj, Instrument.banana.field)
        self.assertEqual(error.msg, "Field defines a relation with model 'Banana', which is either not installed, or is abstract.") 
Example #16
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_two_sided(self):
        A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE)])
        B = self.create_model("B", foreign_keys=[models.ForeignKey('A', models.CASCADE)])
        self.assertRelated(A, [B])
        self.assertRelated(B, [A]) 
Example #17
Source File: test_query.py    From django-seal with MIT License 5 votes vote down vote up
def test_sealed_select_related_non_sealable_model(self):
        class NonSealableLocation(models.Model):
            class Meta:
                db_table = Location._meta.db_table

        class NonSealableSeaLion(models.Model):
            location = models.ForeignKey(NonSealableLocation, models.CASCADE)

            class Meta:
                db_table = SeaLion._meta.db_table
        queryset = SealableQuerySet(model=NonSealableSeaLion)
        instance = queryset.select_related('location').seal().get()
        self.assertTrue(instance._state.sealed)
        self.assertTrue(instance.location._state.sealed) 
Example #18
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_intermediate_m2m_extern_fk(self):
        A = self.create_model("A", foreign_keys=[models.ManyToManyField('B', through='T')])
        B = self.create_model("B")
        Z = self.create_model("Z")
        T = self.create_model("T", foreign_keys=[
            models.ForeignKey('A', models.CASCADE),
            models.ForeignKey('B', models.CASCADE),
            models.ForeignKey('Z', models.CASCADE),
        ])
        self.assertRelated(A, [B, T, Z])
        self.assertRelated(B, [A, T, Z])
        self.assertRelated(T, [A, B, Z])
        self.assertRelated(Z, [A, B, T]) 
Example #19
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_intermediate_m2m(self):
        A = self.create_model("A", foreign_keys=[models.ManyToManyField('B', through='T')])
        B = self.create_model("B")
        T = self.create_model("T", foreign_keys=[
            models.ForeignKey('A', models.CASCADE),
            models.ForeignKey('B', models.CASCADE),
        ])
        self.assertRelated(A, [B, T])
        self.assertRelated(B, [A, T])
        self.assertRelated(T, [A, B]) 
Example #20
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_real_apps(self):
        """
        Including real apps can resolve dangling FK errors.
        This test relies on the fact that contenttypes is always loaded.
        """
        new_apps = Apps()

        class TestModel(models.Model):
            ct = models.ForeignKey("contenttypes.ContentType", models.CASCADE)

            class Meta:
                app_label = "migrations"
                apps = new_apps

        # If we just stick it into an empty state it should fail
        project_state = ProjectState()
        project_state.add_model(ModelState.from_model(TestModel))
        with self.assertRaises(ValueError):
            project_state.apps

        # If we include the real app it should succeed
        project_state = ProjectState(real_apps=["contenttypes"])
        project_state.add_model(ModelState.from_model(TestModel))
        rendered_state = project_state.apps
        self.assertEqual(
            len([x for x in rendered_state.get_models() if x._meta.app_label == "migrations"]),
            1,
        ) 
Example #21
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_intermediate_m2m_self(self):
        A = self.create_model("A", foreign_keys=[models.ManyToManyField('A', through='T')])
        T = self.create_model("T", foreign_keys=[
            models.ForeignKey('A', models.CASCADE),
            models.ForeignKey('A', models.CASCADE),
        ])
        self.assertRelated(A, [T])
        self.assertRelated(T, [A]) 
Example #22
Source File: tests.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_foreign_key_swapped(self):
        with isolate_lru_cache(apps.get_swappable_settings_name):
            # It doesn't matter that we swapped out user for permission;
            # there's no validation. We just want to check the setting stuff works.
            field = models.ForeignKey("auth.Permission", models.CASCADE)
            name, path, args, kwargs = field.deconstruct()

        self.assertEqual(path, "django.db.models.ForeignKey")
        self.assertEqual(args, [])
        self.assertEqual(kwargs, {"to": "auth.Permission", "on_delete": models.CASCADE})
        self.assertEqual(kwargs['to'].setting_name, "AUTH_USER_MODEL") 
Example #23
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_base_to_subclass_fk(self):
        A = self.create_model("A", foreign_keys=[models.ForeignKey('Z', models.CASCADE)])
        B = self.create_model("B", bases=(A,))
        Y = self.create_model("Y")
        Z = self.create_model("Z", bases=(Y,))
        self.assertRelated(A, [B, Y, Z])
        self.assertRelated(B, [A, Y, Z])
        self.assertRelated(Y, [A, B, Z])
        self.assertRelated(Z, [A, B, Y]) 
Example #24
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_circle(self):
        A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE)])
        B = self.create_model("B", foreign_keys=[models.ForeignKey('C', models.CASCADE)])
        C = self.create_model("C", foreign_keys=[models.ForeignKey('A', models.CASCADE)])
        self.assertRelated(A, [B, C])
        self.assertRelated(B, [A, C])
        self.assertRelated(C, [A, B]) 
Example #25
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_ignore_order_wrt(self):
        """
        Makes sure ProjectState doesn't include OrderWrt fields when
        making from existing models.
        """
        new_apps = Apps()

        class Author(models.Model):
            name = models.TextField()

            class Meta:
                app_label = "migrations"
                apps = new_apps

        class Book(models.Model):
            author = models.ForeignKey(Author, models.CASCADE)

            class Meta:
                app_label = "migrations"
                apps = new_apps
                order_with_respect_to = "author"

        # Make a valid ProjectState and render it
        project_state = ProjectState()
        project_state.add_model(ModelState.from_model(Author))
        project_state.add_model(ModelState.from_model(Book))
        self.assertEqual(
            [name for name, field in project_state.models["migrations", "book"].fields],
            ["id", "author"],
        ) 
Example #26
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_nested_fk(self):
        A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE)])
        B = self.create_model("B", foreign_keys=[models.ForeignKey('C', models.CASCADE)])
        C = self.create_model("C")
        self.assertRelated(A, [B, C])
        self.assertRelated(B, [A, C])
        self.assertRelated(C, [A, B]) 
Example #27
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_fk_through_proxy(self):
        A = self.create_model("A")
        B = self.create_model("B", bases=(A,), proxy=True)
        C = self.create_model("C", bases=(B,), proxy=True)
        D = self.create_model("D", foreign_keys=[models.ForeignKey('C', models.CASCADE)])
        self.assertRelated(A, [B, C, D])
        self.assertRelated(B, [A, C, D])
        self.assertRelated(C, [A, B, D])
        self.assertRelated(D, [A, B, C]) 
Example #28
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_sanity_check_to(self):
        field = models.ForeignKey(UnicodeModel, models.CASCADE)
        with self.assertRaisesMessage(
            ValueError,
            'ModelState.fields cannot refer to a model class - "field.to" does. '
            'Use a string reference instead.'
        ):
            ModelState('app', 'Model', [('field', field)]) 
Example #29
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_order_with_respect_to_private_field(self):
        class PrivateFieldModel(models.Model):
            content_type = models.ForeignKey('contenttypes.ContentType', models.CASCADE)
            object_id = models.PositiveIntegerField()
            private = GenericForeignKey()

            class Meta:
                order_with_respect_to = 'private'

        state = ModelState.from_model(PrivateFieldModel)
        self.assertNotIn('order_with_respect_to', state.options) 
Example #30
Source File: test_state.py    From django-sqlserver with MIT License 5 votes vote down vote up
def test_direct_hidden_fk(self):
        A = self.create_model("A", foreign_keys=[models.ForeignKey('B', models.CASCADE, related_name='+')])
        B = self.create_model("B")
        self.assertRelated(A, [B])
        self.assertRelated(B, [A])