Django migrations detect the same change many times

96 views Asked by At

I have a model like this:

MyModel(models.Model):
    ...
    date_start = models.DateTimeField(
        auto_now=True,
        editable=True
    )

    date_end = models.DateTimeField(
        default=datetime.now() + relativedelta(months=3)
    )

...

I modified the date_end field before, and I did the migrations, it is working properly, but now it is still detecting that change as a new migration. Any idea? Thanks in advance.

1

There are 1 answers

2
Daniel Roseman On BEST ANSWER

The problem is that you are calling datetime.now() in the default parameter of the definition. That means that the default changes each time you start Django, so the system thinks you need a new migration.

You should wrap that calculation into a lambda function, which will be called as necessary:

date_end = models.DateTimeField(
    default=lambda: datetime.now() + relativedelta(months=3)
)

Edit

If the lambda causes problems, you can move the code into a separate function and pass that as the default instead:

def default_end():
    return datetime.now() + relativedelta(months=3)

...

date_end = models.DateTimeField(
        default=default_end
)

Note here we're passing the function object, not the result, as the default param.