Why can't I delete a custom function in django models migration?

Viewed 23

I created a custom function to use in another class

models.py

class DateRangeFunc(models.Func):
    function = "daterange"
    output_field = DateRangeField()

class Foo(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=256)
    start_datetime = models.DateField()
    end_datetime = models.DateField()

    class Meta:
        constraints = [
            ExclusionConstraint(
                name="exclude_overlapping",
                expressions=(
                    (
                        DateRangeFunc(
                            "start_datetime", "end_datetime", RangeBoundary()
                        ),
                        RangeOperators.OVERLAPS,
                    ),

                ),
            ),
        ]

DateRangeFunc is the custom method I created to help write an exclusion constraint.

I want to delete the Foo model as well as the DateRangeFunc class because both are not used anymore.

When I try to makemigrations after removing both from models.py I get the following error:

File "foo/migrations/0012_auto_20220907_1238.py", line 31, in Migration
    constraint=django.contrib.postgres.constraints.ExclusionConstraint(expressions=((foo.models.DateRangeFunc('start_datetime', 'end_datetime', django.contrib.postgres.fields.ranges.RangeBoundary()), '&&')), name='exclude_overlapping'),
AttributeError: module 'foo.models' has no attribute 'DateRangeFunc'

because it is still present in the old migration file 0012_auto_20220907_1238.py

https://docs.djangoproject.com/en/4.1/topics/migrations/#considerations-when-removing-model-fields

I should be able to add a system_check_removed_details if necessary (it is not in my case) and then squash -> remove models -> remove migration file. i.e.

"Keep this stub field for as long as any migrations which reference the field exist. For example, after squashing migrations and removing the old ones, you should be able to remove the field completely."

However, I can't run a squash because the same error occurs. That class doesn't seem to be able to be deleted the same way other classes (models). A similar SO post: Delete unused functions from Django models. Migrations error

explains what I want to be able to do, but there doesn't seem to be a working answer (I have tried the suggestions in the comments)

My question is why can't I delete a function like I can delete a model and if I can, how?

1 Answers

try to delete all related migrations and then run commands makemigrations and migrate.

Related