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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #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_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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
Source File: state.py    From django-river with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.field_name = None
        kwargs['null'] = True
        kwargs['blank'] = True
        kwargs['to'] = '%s.%s' % (State._meta.app_label, State._meta.object_name)
        kwargs['on_delete'] = kwargs.get('on_delete', CASCADE)
        kwargs['related_name'] = "+"
        super(StateField, self).__init__(*args, **kwargs) 
Example #17
Source File: test_encrypted.py    From django-cryptography with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_base_fields(self):
        class Related(models.Model):
            field = encrypt(
                models.ForeignKey('fields.EncryptedIntegerModel',
                                  models.CASCADE))

            class Meta:
                app_label = 'myapp'

        obj = Related()
        errors = obj.check()
        self.assertEqual(1, len(errors))
        self.assertEqual('encrypted.E002', errors[0].id) 
Example #18
Source File: models.py    From django-tenants with MIT License 5 votes vote down vote up
def _drop_schema(self, force_drop=False):
        """ Drops the schema"""
        connection = connections[get_tenant_database_alias()]
        has_schema = hasattr(connection, 'schema_name')
        if has_schema and connection.schema_name not in (self.schema_name, get_public_schema_name()):
            raise Exception("Can't delete tenant outside it's own schema or "
                            "the public schema. Current schema is %s."
                            % connection.schema_name)

        if has_schema and schema_exists(self.schema_name) and (self.auto_drop_schema or force_drop):
            self.pre_drop()
            cursor = connection.cursor()
            cursor.execute('DROP SCHEMA "%s" CASCADE' % self.schema_name) 
Example #19
Source File: fields.py    From gro-api with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, to_field=None, rel_class=LayoutManyToOneRel, \
            db_constraint=True, **kwargs):
        if to_field:
            self.to_field = to_field
        if 'db_index' not in kwargs:
            kwargs['db_index'] = True
        self.db_constraint = db_constraint
        kwargs['rel'] = rel_class(
            self, to_field, 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),
        )
        LayoutForeignObject.__init__(self, ['self'], [to_field], **kwargs) 
Example #20
Source File: fields.py    From django-modelcluster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        kwargs.setdefault('on_delete', CASCADE)
        super(ParentalKey, self).__init__(*args, **kwargs) 
Example #21
Source File: test_slug_fields.py    From django-localized-fields with MIT License 5 votes vote down vote up
def test_populate_multiple_from_fields_fk():
        """Tests whether populating the slug from multiple fields works
        correctly."""

        model_fk = get_fake_model({"name": LocalizedField()})

        model = get_fake_model(
            {
                "title": LocalizedField(),
                "other": models.ForeignKey(model_fk, on_delete=models.CASCADE),
                "slug": LocalizedUniqueSlugField(
                    populate_from=("title", "other.name")
                ),
            }
        )

        other = model_fk.objects.create(name={settings.LANGUAGE_CODE: "swen"})

        obj = model()
        for lang_code, lang_name in settings.LANGUAGES:
            obj.other_id = other.id
            obj.title.set(lang_code, "title %s" % lang_name)

        obj.save()

        for lang_code, lang_name in settings.LANGUAGES:
            assert (
                obj.slug.get(lang_code) == "title-%s-swen" % lang_name.lower()
            ) 
Example #22
Source File: test_admin.py    From django-localized-fields with MIT License 5 votes vote down vote up
def setUpClass(cls):
        """Creates the test model in the database."""

        super(LocalizedFieldsAdminMixinTestCase, cls).setUpClass()

        cls.TestRelModel = get_fake_model({"description": LocalizedField()})
        cls.TestModel = get_fake_model(
            {
                "title": LocalizedField(),
                "rel": models.ForeignKey(
                    cls.TestRelModel, on_delete=models.CASCADE
                ),
            }
        ) 
Example #23
Source File: fields.py    From django-currentuser with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.on_update = kwargs.pop("on_update", False)
        self._warn_for_shadowing_args(*args, **kwargs)

        if "on_delete" not in kwargs:
            kwargs["on_delete"] = models.CASCADE

        if self.on_update:
            kwargs["editable"] = False
            kwargs["blank"] = True

        kwargs.update(self.defaults)
        super(CurrentUserField, self).__init__(**kwargs) 
Example #24
Source File: test_form_submission.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_form(self):
        field = self.get_field(FormSubmission, "form")
        self.assertModelPKField(field, Form, models.CASCADE) 
Example #25
Source File: test_form_settings.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_form(self):
        field = self.get_field(AbstractFormSetting, "form")
        self.assertModelField(field, models.OneToOneField)
        self.assertEqual(field.remote_field.model, "wagtailstreamforms.Form")
        self.assertEqual(field.remote_field.on_delete, models.CASCADE)
        self.assertEqual(field.remote_field.related_name, "advanced_settings") 
Example #26
Source File: test_form_submission_file.py    From wagtailstreamforms with MIT License 5 votes vote down vote up
def test_submission(self):
        field = self.get_field(FormSubmissionFile, "submission")
        self.assertModelPKField(field, FormSubmission, models.CASCADE) 
Example #27
Source File: related.py    From python with Apache License 2.0 5 votes vote down vote up
def __init__(self, to, on_delete=None, to_field=None, **kwargs):
        kwargs['unique'] = True

        if on_delete is None:
            warnings.warn(
                "on_delete will be a required arg for %s in Django 2.0. Set "
                "it to models.CASCADE on models and in existing migrations "
                "if you want to maintain the current default behavior. "
                "See https://docs.djangoproject.com/en/%s/ref/models/fields/"
                "#django.db.models.ForeignKey.on_delete" % (
                    self.__class__.__name__,
                    get_docs_version(),
                ),
                RemovedInDjango20Warning, 2)
            on_delete = CASCADE

        elif not callable(on_delete):
            warnings.warn(
                "The signature for {0} will change in Django 2.0. "
                "Pass to_field='{1}' as a kwarg instead of as an arg.".format(
                    self.__class__.__name__,
                    on_delete,
                ),
                RemovedInDjango20Warning, 2)
            to_field = on_delete
            on_delete = CASCADE  # Avoid warning in superclass

        super(OneToOneField, self).__init__(to, on_delete, to_field=to_field, **kwargs) 
Example #28
Source File: related.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def __init__(self, to, on_delete=None, to_field=None, **kwargs):
        kwargs['unique'] = True

        if on_delete is None:
            warnings.warn(
                "on_delete will be a required arg for %s in Django 2.0. "
                "Set it to models.CASCADE if you want to maintain the current default behavior. "
                "See https://docs.djangoproject.com/en/%s/ref/models/fields/"
                "#django.db.models.ForeignKey.on_delete" % (
                    self.__class__.__name__,
                    get_docs_version(),
                ),
                RemovedInDjango20Warning, 2)
            on_delete = CASCADE

        elif not callable(on_delete):
            warnings.warn(
                "The signature for {0} will change in Django 2.0. "
                "Pass to_field='{1}' as a kwarg instead of as an arg.".format(
                    self.__class__.__name__,
                    on_delete,
                ),
                RemovedInDjango20Warning, 2)
            to_field = on_delete
            on_delete = CASCADE  # Avoid warning in superclass

        super(OneToOneField, self).__init__(to, on_delete, to_field=to_field, **kwargs) 
Example #29
Source File: test_listcharfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_base_fields(self):
        class InvalidListCharModel2(TemporaryModel):
            field = ListCharField(
                models.ForeignKey("testapp.Author", on_delete=models.CASCADE),
                max_length=32,
            )

        errors = InvalidListCharModel2.check(actually_check=True)
        assert len(errors) == 1
        assert errors[0].id == "django_mysql.E005"
        assert "Base field for list must be" in errors[0].msg 
Example #30
Source File: test_listtextfield.py    From django-mysql with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_invalid_base_fields(self):
        class InvalidListTextModel2(TemporaryModel):
            field = ListTextField(
                models.ForeignKey("testapp.Author", on_delete=models.CASCADE),
                max_length=32,
            )

        errors = InvalidListTextModel2.check(actually_check=True)
        assert len(errors) == 1
        assert errors[0].id == "django_mysql.E005"
        assert "Base field for list must be" in errors[0].msg